0

I want to get current time and add it with an integer of hours. Example now is 11.00pm, May 12, 2019. I want to add 3 hours more. So the result would be 2.00 am May 13, 2019. Please help me to datetime + hours(integer type)

import datetime

currentDT = datetime.datetime.now()
print('Now is: '+ str(currentDT))
hours = int(input()) #any hours you want
result = currentDT + hours #it will get the errors here

1 Answers1

4

Use datetime.now to obtain the current time, and add a datetime.timedelta:

from datetime import datetime, timedelta

n_hours = 3
date = datetime.now() + timedelta(hours=n_hours)

print(datetime.now())
# 2019-05-12 19:16:51.651376

print(date)
# 2019-05-12 22:16:51.464890
yatu
  • 86,083
  • 12
  • 84
  • 139
  • how about input() is a random number? I mean I wanna add any integer number here, it is not a default number. – Brian Huynh May 12 '19 at 17:45
  • Just use a variable? – yatu May 12 '19 at 17:47
  • @BrianHuynh Change the `hours` argument in the `timedelta` function to whatever you want. You specified 3 hours in your post and hence 3 hours was put in the answer. – rayryeng May 12 '19 at 18:07
  • You're welcome @BrianHuynh. As mentioned, don't forget to accept (green check under the voting options) – yatu May 13 '19 at 09:21
  • 2
    Thank you Yatu. Thank you stackover give me hope that I can code and do the right job for myself. Thank you 5* from Vietnam – Brian Huynh May 13 '19 at 16:45