#592 Conversion of UTC timestamp to localtime is wrong at STD/DST

closed-fixed
5
2012-05-10
2012-05-08
Brian Matthews
No

I am not sure if this error is in TimeZoneInfo or datetime.

I am running my PC in Pacific time, so I have a way to
easily check the results. The script below converts UTC timestamps into a
datetime in the Pacific time zone. The result for PST 2:00 AM on 2011-11-06 is wrong.
Doing the same conversion using localtime() is correct.
During the ambiguous localtime hour on 6-Nov, 2:00 AM should only appear once. 1:00 AM should appear twice.

>>> from win32timezone import TimeZoneInfo
>>> from datetime import datetime
>>> import calendar
>>> import time
>>>
>>> tzi = TimeZoneInfo('Pacific Standard Time')
>>> tzutc = TimeZoneInfo('Coordinated Universal Time')
>>>
>>> def fromtimestamp_to_timetuple(timestamp):
... tm = time.gmtime(timestamp)
... tz1 = datetime(tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour,
... tm.tm_min, tm.tm_sec, tzinfo=tzutc)
... tz_time = tz1.astimezone(tzi)
... return tz_time
...
>>> print fromtimestamp_to_timetuple(1320573600).timetuple()
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=6, tm_hour=2, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=310, tm_isdst=0)
>>> print fromtimestamp_to_timetuple(1320570000).timetuple()
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=6, tm_hour=2, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=310, tm_isdst=0)
>>> print fromtimestamp_to_timetuple(1320566400).timetuple()
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=6, tm_hour=1, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=310, tm_isdst=1)
>>>
>>> print time.strftime('%c', time.localtime(1320573600))
11/06/11 02:00:00
>>> print time.strftime('%c', time.localtime(1320570000))
11/06/11 01:00:00
>>> print time.strftime('%c', time.localtime(1320566400))
11/06/11 01:00:00

Discussion

  • Brian Matthews
    Brian Matthews
    2012-05-08

    NOTE: This is a problem only at precisely the end of the hour. It is using the most recent patches.

     
  • I've pushed two more changesets that address this issue. Thanks again for providing a detailed report helping me create tests to capture and resolve the problem.

    The latest changeset also now raises an AmbiguousTimeError if .utcoffset or .dst is called for a datetime which could be either. It includes its own tests and doesn't cause any of the existing tests to fail.

    Please take a look at the latest revisions and please don't hesitate to let me know if you encounter any other issues.

     
    • status: open --> closed-fixed