Python: time.mktime returning the same value for different dates
I was working on some python scripts to calculate the time spent since an older date, and surprisingly got a negative result. I realized that the problem may be in the time.mktime function. Let's get this code:
import time
import datetime
before = datetime.datetime(2010, 10, 17, 0, 0, 0)
after = datetime.datetime(2010, 10, 17, 1,开发者_如何学Python 0, 0)
print "%s = %f" % (before, time.mktime(before.timetuple()))
print "%s = %f" % (after, time.mktime(after.timetuple()))
On my Linux 32-bit Python 2.6.4, the output is:
2010-10-17 00:00:00 = 1287284400.000000
2010-10-17 01:00:00 = 1287284400.000000
The same timestamp for different times! Am I doing something wrong?
No. DST in Brazil started on October 17, 2010, so one hour is missing.
Note that mktime gives you the representation of your local time, with Daylight Savings if applicable to your system locale. This can lead to some odd behaviors.
You may prefer calendar.timegm which gives you UTC time.
精彩评论