gkarya42
gkarya42

Reputation: 429

Standard UTC offset (Without DST) for a give TimeZone in Python

I have a requirement where i need to group several timezone codes based on standrad UTC offset (Without DST), for example - all the time zone with standard UTC offset value between 4 and 6 will be part of one group and so one.

How can i get the standard UTC offset for a timezone using timezone code?

I tried below method but it gives me the offset with DST.

pytz.timezone('Asia/Jerusalem').localize(datetime.datetime(2011,1,1)).strftime('%z')

Upvotes: 2

Views: 1002

Answers (1)

FObersteiner
FObersteiner

Reputation: 25544

You could make use of the .dst() method; it gives you the timedelta of the DST. If subtracted from the .utcoffset(), you get the "standard" UTC offset of the time zone.

from datetime import datetime
from zoneinfo import ZoneInfo

dt_woDST = datetime(2011,1,1, tzinfo=ZoneInfo('Asia/Jerusalem'))
# 2011-01-01 00:00:00+02:00 
dt_DST = datetime(2011,6,1, tzinfo=ZoneInfo('Asia/Jerusalem'))
# 2011-06-01 00:00:00+03:00

utcoff0 = (dt_woDST.utcoffset()-dt_woDST.dst()).total_seconds()
utcoff1 = (dt_DST.utcoffset()-dt_DST.dst()).total_seconds()

print(utcoff0, utcoff0 == utcoff1)
# 7200.0 True

Note: I'm using Python 3.9's zoneinfo here; of course this also works with datetime objects that you localized with pytz timezone objects.

Upvotes: 3

Related Questions