简体   繁体   中英

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')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM