For example, if the start time is 8:00am how do I calculate the time after 20 hours have passed?
-
[Modular arithmatic](http://en.wikipedia.org/wiki/Modular_arithmetic) – Liam McInroy Oct 31 '14 at 01:24
-
so you want to do 20 hours to your timer? – smushi Oct 31 '14 at 01:25
-
@smushi my program is supposed to ask for user input after every 20 hours (not in real time, but hypothetically) and calculate the current time after every 20 hours. – eskoka Oct 31 '14 at 01:28
-
@eskoka upvote answer as well please – smushi Oct 31 '14 at 01:47
2 Answers
Need to use something like timedelta
from datetime import datetime, timedelta
twenty_hours= datetime.now() + timedelta(hours=20)
ofcourse you'll change datetime.now() to your 8am or what ever time you wish
>>> format(twenty_hours, '%H:%M:%S')
'23:24:31'

- 701
- 6
- 17
-
it is wrong if there is a DST transition in between. It may return the local time that is earlier or later than 20 hours. – jfs Dec 14 '15 at 12:42
-
There are at least two possible interpretations of your question:
Find the local time that is exactly 20 hours from now:
#!/usr/bin/env python3 from datetime import datetime, timedelta, timezone now = datetime.now(timezone.utc) # current time in UTC in20hours = (now + timedelta(hours=20)).astimezone() # local time in 20 hours print("Local time in 20 hours: {in20hours:%I:%M %p}".format(**vars())) # AM/PM
Find the time while ignoring any changes in the local UTC offset (due to DST transitions or any other reason):
#!/usr/bin/env python from datetime import datetime, timedelta, timezone now = datetime.now() # local time by20hours = now + timedelta(hours=20) # move clock by 20 hours print("Move clock by 20 hours: {by20hours:%I:%M %p}".format(**vars())) # AM/PM
Related: python time + timedelta equivalent
Both methods produce the same result if the local utc offset won't change during the next 20 hours. Otherwise the second method fails, to find the time after 20 hours have passed.
You might need the second method if you want to do something at the same local time no matter how many hours have passed in between e.g., if you want to get up at 6am no matter whether 24 hours have passed or not. See How can I subtract a day from a Python date?
More details on the time arithmetics if you are working with local time see at Find if 24 hrs have passed between datetimes - Python.