I used pytz
to generate a TZINFOS
mapping:
from datetime import datetime as dt
import pytz
from dateutil.tz import gettz
from pytz import utc
from dateutil import parser
def gen_tzinfos():
for zone in pytz.common_timezones:
try:
tzdate = pytz.timezone(zone).localize(dt.utcnow(), is_dst=None)
except pytz.NonExistentTimeError:
pass
else:
tzinfo = gettz(zone)
if tzinfo:
yield tzdate.tzname(), tzinfo
TZINFOS
Usage
>>> TZINFOS = dict(gen_tzinfos())
>>> TZINFOS
{ +02 : tzfile( /usr/share/zoneinfo/Antarctica/Troll ),
+03 : tzfile( /usr/share/zoneinfo/Europe/Volgograd ),
+04 : tzfile( Europe/Ulyanovsk ),
+05 : tzfile( /usr/share/zoneinfo/Indian/Kerguelen ),
...
WGST : tzfile( /usr/share/zoneinfo/America/Godthab ),
WIB : tzfile( /usr/share/zoneinfo/Asia/Pontianak ),
WIT : tzfile( /usr/share/zoneinfo/Asia/Jayapura ),
WITA : tzfile( /usr/share/zoneinfo/Asia/Makassar ),
WSDT : tzfile( /usr/share/zoneinfo/Pacific/Apia ),
XJT : tzfile( /usr/share/zoneinfo/Asia/Urumqi )}
parser
Usage
>>> date_str = Sat, 11/01/09 8:00PM EST
>>> tzdate = parser.parse(date_str, tzinfos=TZINFOS)
>>> tzdate.astimezone(utc)
datetime.datetime(2009, 11, 2, 1, 0, tzinfo=<UTC>)
The UTC conversion is needed since there are many timezones available for each abbreviation. Since TZINFOS
is a dict
, it only has the last timezone per abbreviation. And you may not get the one you were expecting pre conversion.
>>> tzdate
datetime.datetime(2009, 11, 1, 20, 0, tzinfo=tzfile( /usr/share/zoneinfo/America/Port-au-Prince ))