eskoka
eskoka

Reputation: 97

Calculate time after X hours?

For example, if the start time is 8:00am how do I calculate the time after 20 hours have passed?

Upvotes: 2

Views: 2842

Answers (2)

jfs
jfs

Reputation: 414207

There are at least two possible interpretations of your question:

  1. 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
    
  2. 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.

Upvotes: 1

smushi
smushi

Reputation: 719

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'

Upvotes: 2

Related Questions