Using pytz
, I know how to get a listing a Timezone names, but I would like to get all possible Timezone abbreviations for each Timezone name:
import pytz
list(pytz.common_timezones)
['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa',...]
What I am looking for is given any Timezone abbreviation, example PST or PDT, ignoring current datetime (e.g. now), return the all possible Timezone name, in this case a list that would include America/Los_Angeles.
Thanks
Since you wish to ignore the current datetime, it sounds like you want to find
any timezone which ever used the given abbreviation at any time in the
past. That information is in the Olson database and accessible through
pytz. However, pytz stores this information in the private attribute,
tzone._transition_info
:
import collections
import datetime as DT
import pytz
tzones = collections.defaultdict(set)
abbrevs = collections.defaultdict(set)
for name in pytz.all_timezones:
tzone = pytz.timezone(name)
for utcoffset, dstoffset, tzabbrev in getattr(
tzone, '_transition_info', [[None, None, DT.datetime.now(tzone).tzname()]]):
tzones[tzabbrev].add(name)
abbrevs[name].add(tzabbrev)
The reason for the third (default) argument to gettattr
is to handle a few
timezones, such as Africa/Bujumbura
, which never had any transitions. So the
abbreviation in these cases is the current abbreviation.
In [94]: tzones['PST']
Out[94]:
{'America/Bahia_Banderas',
'America/Boise',
'America/Creston',
'America/Dawson',
'America/Dawson_Creek',
'America/Ensenada',
'America/Hermosillo',
'America/Inuvik',
'America/Juneau',
'America/Los_Angeles',
'America/Mazatlan',
'America/Metlakatla',
'America/Santa_Isabel',
'America/Sitka',
'America/Tijuana',
'America/Vancouver',
'America/Whitehorse',
'Canada/Pacific',
'Canada/Yukon',
'Mexico/BajaNorte',
'Mexico/BajaSur',
'PST8PDT',
'Pacific/Pitcairn',
'US/Pacific',
'US/Pacific-New'}
In [95]: tzones['PDT']
Out[95]:
{'America/Boise',
'America/Dawson',
'America/Dawson_Creek',
'America/Ensenada',
'America/Juneau',
'America/Los_Angeles',
'America/Metlakatla',
'America/Santa_Isabel',
'America/Sitka',
'America/Tijuana',
'America/Vancouver',
'America/Whitehorse',
'Canada/Pacific',
'Canada/Yukon',
'Mexico/BajaNorte',
'PST8PDT',
'US/Pacific',
'US/Pacific-New'}
In [97]: abbrevs['America/Los_Angeles']
Out[97]: {'LMT', 'PDT', 'PPT', 'PST', 'PWT'}
As Paul points out, note that timezone abbreviations are ambiguous -- they do not necessarily map to timezones with the same utcoffset. For example, both Asia/Shanghai
and US/Central
use the CST
timezone abbreviation.
In [242]: 'Asia/Shanghai' in tzones['CST']
Out[242]: True
In [243]: 'US/Central' in tzones['CST']
Out[243]: True