I have an issue comparing outputs with dateutil
and pytz
. I'm creating a aware datetime object (UTC) and then converting to a given time zone, but I get different answers. I suspect that dateutil sometimes gives wrong results because it has problems taking into account daylight saving time (at least, I read a comment about it) but I can't find confirmation or a fix to that issue. This is the code:
import dateutil
u = dateutil.tz.tzutc()
date1 = datetime.datetime(2010, 5, 2, 11, 10, tzinfo=u)
# 2010-05-02 11:10:00+00:00
u2 = dateutil.tz.gettz('America/Chicago')
date2 = datetime.datetime(2010, 5, 2, 11, 10, tzinfo=u2)
# 2010-05-02 11:10:00-05:00
import pytz
u = pytz.timezone('UTC')
date1 = datetime.datetime(2010, 5, 2, 11, 10, tzinfo=u)
# 2010-05-02 11:10:00+00:00
u2 = pytz.timezone('America/Chicago')
date2 = datetime.datetime(2010, 5, 2, 11, 10, tzinfo=u2)
# 2010-05-02 11:10:00-06:00
So, what could be the problem here?
UPDATE:
I just tried this:
print u2.normalize(date1.astimezone(u2))
# 2010-05-02 06:10:00-05:00
So pytz needs normalize
to consider DST?
UPDATE 2:
It seemed as if pytz and dateutil don't give the answer for America/Argentina/San_Luis but this works:
import pytz, dateutil, datetime
now = datetime.datetime.now()
for zone in pytz.all_timezones:
utc_dateutil = dateutil.tz.tzutc()
utcdate_dateutil = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute, tzinfo=utc_dateutil)
zone_dateutil = dateutil.tz.gettz(zone)
newzone_dateutil = utcdate_dateutil.astimezone(zone_dateutil)
utc_pytz = pytz.timezone('UTC')
utcdate_pytz = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute, tzinfo=utc_pytz)
zone_pytz = pytz.timezone(zone)
newzone_pytz = utcdate_pytz.astimezone(zone_pytz)
assert newzone_dateutil == newzone_pytz
Am I missing something?
America/Chicago
time zone? Try it on another machine? I can't reproduce this behaviour. – Clemonspytz
is quite stupid when you apply it without usinglocalize
. It just uses the first thing in the database for that zone, which in some cases is complete nonsense - see #11442683. It certainly doesn't account for DST. – Antipodes