244

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?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Shiva Krishna Bavandla
  • 25,548
  • 75
  • 193
  • 313
  • 18
    To get the current time formatted that way, have a look at `datetime.now().strftime('%H:%M:%S')` – eumiro Dec 03 '12 at 14:24

4 Answers4

515
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

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • 2
    Why isn't this the Best Answer? Is there any side effects? unreported bug? – Braza Mar 28 '16 at 15:03
  • 8
    @Braza the OP just hasn't chosen to accept it. No side effects or bugs. – Jon Clements Mar 28 '16 at 15:13
  • @JonClements Thank you for your reply :). I tested it and I confirm. – Braza Mar 28 '16 at 15:52
  • 3
  • 1
    The question asks how to **add** hours, but **subtracting** hours could be done in two ways: 1) Use the subtraction operator (`-`) instead of addition operator (`+`); according to the documentation "`timedelta` objects support certain additions and subtractions with date and `datetime` objects " 2) Pass a negative value to any of the `timedelta` parameters; according to [the documentation](https://docs.python.org/2/library/datetime.html), "Arguments may be ints, longs, or floats, and may be positive or negative." – Nate Anderson Mar 04 '17 at 23:36
  • 1
    Its not working with python2.7. Whats the solution for this? – shiva Jul 06 '18 at 12:48
47

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

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
3

This is an answer which is significant for nowadays (python 3.9 or later).

Use strptime to create a datetime object from the timestring. Add 9 hours with timedelta, and match the time format with the timestring you have.

    from datetime import datetime, timedelta
    from zoneinfo import ZoneInfo

    time_format = "%H:%M:%S"

    timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)

    #You can then apply custom time formatting as well as a timezone.

    TIMEZONE = [Add a timezone] #https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

    custom_time_format = "%H:%M"

    time_modification = datetime.fromtimestamp(timestring.timestamp(), ZoneInfo(TIMEZONE)).__format__(custom_time_format)

While I think it's more meaningful to apply a timezone, you don't necessarily need to, so you can also simply do that:

time_format = "%H:%M:%S"

timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)

time_modification = datetime.fromtimestamp(timestring.timestamp())

datetime

https://docs.python.org/3/library/datetime.html

strftime-and-strptime-format-codes

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

timedelta

https://docs.python.org/3/library/datetime.html#datetime.timedelta

zoneinfo

https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo

Conor
  • 327
  • 6
  • 15
2

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))
bbartling
  • 3,288
  • 9
  • 43
  • 88
  • `utc_time = dt.replace(tzinfo=timezone.utc)` is unnecessary - tzinfo of `dt` will already be set correctly to timezone.utc Also, you should either import the module or specific classes form it, not both. – FObersteiner Sep 29 '21 at 12:45
  • Any chance you could give me a tip on what that looks like through posting an answer with reference to my answer? I could use this, any help appreciated not a lot of wisdom here. – bbartling Sep 29 '21 at 13:10
  • you mean the imports or tzinfo? Regarding imports, in the first line of your code snippet, you import specific classes from the module, in the second line, you *also* import the whole module (which of course includes the classes). Both methods are ok, just use only one of them to improve readability ;-) – FObersteiner Sep 29 '21 at 13:18