Reputation: 3010
i want to add UTC offset to timezone list from tz database, like: * (UTC +0) Europe/London
For list of timezones i use pytz.common_timezones, but cant retrieve STD utcoffset for timezone, because all methods on timezone object requires dt object, moment of time, when to calculate offset.
It's posible to get STD offset from pytz timezone object without manipulation with specific dates?
Thanks!
Upvotes: 1
Views: 2872
Reputation: 879083
The pytz
tzinfo
objects contain the UTC transition times which mark the boundary between STD and DST. However, accessing this information requires dipping into their private attributes -- in particular,
tzone._utc_transition_times
, tzone._transition_info
. So what follows is fragile -- pytz
does not guarantee you can access the same information the same way in future versions.
Nevertheless, at least for pytz version 2010b, using the attributes above, you can find a date in the most recent period which was in STD. You can then use std_date.strftime('%z')
to print the offset.
import pytz
import datetime as DT
NOW = DT.datetime.now()
ZERO = DT.timedelta(0)
for tname in pytz.common_timezones:
tzone = pytz.timezone(tname)
std_date = None
try:
for utcdate, info in zip(
tzone._utc_transition_times, tzone._transition_info):
utcoffset, dstoffset, tzname = info
if dstoffset == ZERO:
std_date = utcdate
if utcdate > NOW:
break
except AttributeError:
std_date = NOW
std_date = tzone.localize(std_date)
print('{n} UTC{z}'.format(n=tname, z=std_date.strftime('%z')))
prints
Africa/Abidjan UTC+0000
Africa/Accra UTC+0000
Africa/Addis_Ababa UTC+0235
Africa/Algiers UTC+0000
Africa/Asmara UTC+0235
Africa/Bamako UTC+0000
Africa/Bangui UTC+0114
Africa/Banjul UTC+0000
...
Upvotes: 4