How to add hours to current time in python

PythonTimeAddTimedelta

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

Import datetime and timedelta:

>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'

But the better way is:

>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'

You can refer strptime and strftime behavior to better understand how python processes dates and time field

Solution 3 - Python

This works for me working with seconds not hours and also using a function to convert back to UTC time.

from datetime import timezone, datetime, timedelta 
import datetime


def utc_converter(dt):
    dt = datetime.datetime.now(timezone.utc)
    utc_time = dt.replace(tzinfo=timezone.utc)
    utc_timestamp = utc_time.timestamp()
    return utc_timestamp



# create start and end timestamps
_now = datetime.datetime.now()
str_start = str(utc_converter(_now))
_end = _now + timedelta(seconds=10)
str_end = str(utc_converter(_end))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShiva Krishna BavandlaView Question on Stackoverflow
Solution 1 - PythonJon ClementsView Answer on Stackoverflow
Solution 2 - PythonAnshul GoyalView Answer on Stackoverflow
Solution 3 - PythonbbartlingView Answer on Stackoverflow