How to add hours to current time in python

Shiva Krishna Bavandla picture Shiva Krishna Bavandla · Dec 3, 2012 · Viewed 234.3k times · Source

I am able to get the current time as below:

from datetime import datetime
str(datetime.now())[11:19]

Result

'19:43:20'

Now, i am trying to add 9 hours to the above time, how can I add hours to current time in Python?

Answer

Jon Clements picture Jon Clements · Dec 3, 2012
from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

And then use string formatting to get the relevant pieces:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

If you're only formatting the datetime then you can use:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

Or, as @eumiro has pointed out in comments - strftime