Bug in Time module, or in my understanding?

Jay Loden python at jayloden.com
Wed Aug 1 18:49:14 EDT 2007


Joshua J. Kugler wrote:
> I am getting results like these with the time module:
> 
>>>> import time
>>>> int(time.mktime(time.strptime('2007-03-11 02:00:00', '%Y-%m-%d %H:%M
> %S')))
> 1173610800
>>>> int(time.mktime(time.strptime('2007-03-11 03:00:00', '%Y-%m-%d %H:%M
> %S')))
> 1173610800
>>>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1173610800))
> '2007-03-11 03:00:00'
> 
> I know it probably has something to do with daylight savings, but how can I
> get back out that which I put in?  The times concerned are all standard
> time, so how can I keep the time module from asserting its belief that I
> want to convert to daylight savings?
> 
> Incidentally, it only happens with times on 2007-03-11  from 02:00:00 to
> 02:59:59, and not with time data from past years.

I *think* what's happening is that time.strptime() is setting the DST flag to "-1" for Unknown. The docs say this happens by default if it's not specified in the string:

>>> time.strptime('2007-03-11 02:00:00', '%Y-%m-%d %H:%M:%S')
(2007, 3, 11, 2, 0, 0, 6, 70, -1)
>>> time.strptime('2007-03-11 03:00:00', '%Y-%m-%d %H:%M:%S')
(2007, 3, 11, 3, 0, 0, 6, 70, -1)

If you try calling time.mktime() with the flag unset you get the same result for both (note that I'm in an eastern time zone so it doesn't match yours exactly), and if it's set, you get a different result:

>>> time.mktime((2007, 3, 11, 3, 0, 0, 6, 70, -1))
1173596400.0
>>> time.mktime((2007, 3, 11, 2, 0, 0, 6, 70, 0))
1173596400.0
>>> time.mktime((2007, 3, 11, 2, 0, 0, 6, 70, 1))
1173592800.0

Not sure what your input is from, but can you maybe change the string to include the time zone?

>>> time.mktime(time.strptime('2007-03-11 03:00:00 EST', '%Y-%m-%d %H:%M:%S %Z'))
1173600000.0
>>> time.mktime(time.strptime('2007-03-11 02:00:00 EST', '%Y-%m-%d %H:%M:%S %Z'))
1173596400.0

Hope some of this helps

-J



More information about the Python-list mailing list