I'm trying to parse timestamp strings like "Sat, 11/01/09 8:00PM EST"
in Python, but I'm having trouble finding a solution that will handle the abbreviated timezone.
I'm using dateutil
's parse()
function, but it doesn't parse the timezone. Is there an easy way to do this?
That probably won't work because those abbreviations aren't unique. See this page for details. You might wind up just having to manually handle it yourself if you're working with a known set of inputs.
dateutil
'sparser.parse()
accepts as keyword argumenttzinfos
a dictionary of the kind{'EST': -5*3600}
(that is, matching the zone name to GMT offset in seconds). So assuming we have that, we can do:Regarding the content of
tzinfos
, here is how i populated mine:ps. per @Hank Gay time zone naming is not clearly defined. To form my table i used http://www.timeanddate.com/library/abbreviations/timezones/ and http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations . I looked at each conflict and resolved conflicts between obscure and popular names towards the popular (more used ones). There was one - IST - that was not as clear cut (it can mean Indian Standard Time, Iran Standard Time, Irish Standard Time or Israel Standard Time), so i left it out of the table - you may need to chose what to add for it based on your location. Oh - and I left out the Republic of Kiribati with their absurd "look at me i am first to celebrate New Year" GMT+13 and GMT+14 time zones.
The parse() function in dateutil can't handle time zones. The thing I've been using is the %Z formatter and the time.strptime() function. I have no idea how it deals with the ambiguity in time zones, but it seems to tell the difference between CDT and CST, which is all I needed.
Background: I store backup images in directories whose names are timestamps using local time, since I don't have GMT clocks handy at home. So I use time.strptime(d, r"%Y-%m-%dT%H:%M:%S_%Z") to parse the directory names back into an actual time for age analysis.
I used
pytz
to generate aTZINFOS
mapping:TZINFOS
Usageparser
UsageThe UTC conversion is needed since there are many timezones available for each abbreviation. Since
TZINFOS
is adict
, it only has the last timezone per abbreviation. And you may not get the one you were expecting pre conversion.You might try pytz module: http://pytz.sourceforge.net/