Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute the time difference between two time zones in python?

How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware datetime objects and get a timedelta; I want to compare two TimeZone objects and get an offset_hours. Nothing in the datetime library handles this, and neither does pytz.

like image 298
coriolinus Avatar asked Oct 13 '17 19:10

coriolinus


People also ask

How do you calculate time difference between time zones?

Calculating time zones is simple and involves adding or subtracting an hour for every 15 degrees of longitude.

How does Python handle different time zones?

The parameter pytz. timezone allows us to specify the timezone information as a string. We can pass in any available timezone and will get the current date time of that timezone, and it will also print the offset with respect to the UTC. i.e., the difference between UTC timezone(+00:00) and the specified time zone.


2 Answers

from datetime import datetime
from zoneinfo import ZoneInfo

dt = datetime.now() # 2020-09-13
tz0, tz1 = "Europe/Berlin", "US/Eastern" # +2 vs. -4 hours rel. to UTC

utcoff0, utcoff1 = dt.astimezone(ZoneInfo(tz0)).utcoffset(), dt.astimezone(ZoneInfo(tz1)).utcoffset()

print(f"hours offset between {tz0} -> {tz1} timezones: {(utcoff1-utcoff0).total_seconds()/3600}")
>>> hours offset between Europe/Berlin -> US/Eastern timezones: -6.0
  • a way to do this with Python 3.9's standard library.
like image 61
FObersteiner Avatar answered Oct 08 '22 09:10

FObersteiner


Here is a solution using the Python library Pytz which solves the issue of ambiguous times at the end of daylight saving time.


from pytz import timezone
import pandas as pd

def tz_diff(date, tz1, tz2):
    '''
    Returns the difference in hours between timezone1 and timezone2
    for a given date.
    '''
    date = pd.to_datetime(date)
    return (tz1.localize(date) - 
            tz2.localize(date).astimezone(tz1))\
            .seconds/3600

The examples below calculate the difference in hours between UTC and Australia time for the first of January and first of June respectively. Notice how daylight savings are taken into consideration.

utc = timezone('UTC')
aus = timezone('Australia/Sydney')

tz_diff('2017-01-01', utc, aus)

# 11.0

tz_diff('2017-06-01', utc, aus)

# 10.0

Thanks

like image 37
Harry Daniels Avatar answered Oct 08 '22 09:10

Harry Daniels