Python’s date and time APIs are awful. Actually they’re awful in most languages, Java’s were sure terrible. But Python is worse because it has several ways to do things and none of them are really correct. The newish datetime module is better than the old time module and its bizarre “tuple that may or may not be timezone aware” type. But even datetime is stupid about time zones, only supporting UTC or the local computer’s time. You need the add-on pytz to bring in the Olson timezone database to start doing real work, and even then it’s complex.
I have some timestamps, seconds-since-Unix-epoch, which is intrinsically UTC. Unambiguous integers. Now I want to print them in Florida’s timezone, no matter what my computer’s time zone is. Here’s one way:
florida = pytz.timezone('US/Eastern') floridaDatetime = datetime.datetime.fromtimestamp(ts, florida) print floridaDatetime.strftime("%b %d %H:%M")
This seems to work, but the pytz docs admonish “Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones. It is safe for timezones without daylight savings trasitions though, such as UTC” The docs recommend this instead:
florida = pytz.timezone('US/Eastern') utcDatetime = datetime.datetime.fromtimestamp(ts, pytz.utc) floridaDatetime = utcDatetime.astimezone(florida) print floridaDatetime.strftime("%b %d %H:%M")
I’m not positive, but I think my simpler code actually will work as long as I don’t try to do anything fancy with floridaDatetime like arithmetic. The problem is described in detail in the pytz docs: it’s some combination of datetime being limited and that certain timestamps are ambiguous because of DST. So really pytz is encouraging us to always always always only ever do math with UTC time and defer conversion to local timezone to the last possible moment before string output. Which is imminently sensible, if frustratingly verbose.
I think the right library would be a datetime type whose internal representation is always only ever seconds-since-epoch plus desired timezone. That way all the library code can do arithmetic without worrying about DST. I wonder if any other languages do it that way. Python’s got some unfortunate legacy hanging around and I don’t think Python3k tried to fix up the mess.