Part of the problem here is that the strings commonly used to represent time zones are not really unique. “EST” only means “America / New_York” for people in North America. This is a limitation in the C API, and the Python solution is to add all tz functions to any future version at any time if someone wants to write PEP.
You can format and parse the time zone as an offset, but this loses daylight saving time (for example, you cannot distinguish between America / Phoenix and America / Los_Angeles in summer). You can format the time zone as an abbreviation of 3 letters, but you cannot cancel it.
If you want something fuzzy and ambiguous, but usually what you want, you need a third-party library like dateutil .
If you want something really unambiguous, just add the actual name tz to the local datetime string and split it at the other end:
d = datetime.datetime.now(pytz.timezone("America/New_York")) dtz_string = d.strftime(fmt) + ' ' + "America/New_York" d_string, tz_string = dtz_string.rsplit(' ', 1) d2 = datetime.datetime.strptime(d_string, fmt) tz2 = pytz.timezone(tz_string) print dtz_string print d2.strftime(fmt) + ' ' + tz_string
Or ... halfway between the two, you are already using the pytz library, which can parse (according to some arbitrary, but well-defined ambiguity rules) formats such as "EST". So, if you really want this, you can leave %Z on the format side, then pull it out and pytz.timezone() with pytz.timezone() before passing the rest to strptime .
abarnert Feb 07 '13 at 23:55 2013-02-07 23:55
source share