[英]Date/time conversion using time.mktime seems wrong
>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
time.mktime
应该返回自纪元以来的秒数。 因为我在午夜给它一个时间而且这个时期在午夜,所以结果不应该被一天中的秒数整除吗?
简短的回答:因为时区。
Epoch是UTC。
例如,我在IST(爱尔兰标准时间)或UTC + 1。 time.mktime()
是相对于我的时区,所以在我的系统上这是指
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000.0
因为你得到了结果1233378000,这表明你落后我5个小时
>>> (1233378000 - 1233360000) / (60*60)
5
看一下UTC的time.gmtime()
函数。
mktime(...)
mktime(tuple) -> floating point number
Convert a time tuple in local time to seconds since the Epoch.
当地时间......想象一下。
时间元组:
The other representation is a tuple of 9 integers giving local time.
The tuple items are:
year (four digits, e.g. 1998)
month (1-12)
day (1-31)
hours (0-23)
minutes (0-59)
seconds (0-59)
weekday (0-6, Monday is 0)
Julian day (day in the year, 1-366)
DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.
顺便说一下,我们似乎相隔6个小时:
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233356400.0
>>> (1233378000.0 - 1233356400)/(60*60)
6.0
菲尔的答案真的解决了它,但我会详细说明一点。 由于纪元是UTC格式,如果我想将其他时间与时期进行比较,我还需要将它们解释为UTC。
>>> calendar.timegm((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000
>>> 1233360000 / (60*60*24)
14275
到时候的元组转换为时间戳治疗是UTC时间,我得到了一些它是由以秒为单位,每天数整除。
我可以用这个来将日期转换为一个从纪元日开始的日期,这是我最终追求的。
有趣。 我不知道,但我确实试过这个:
>>> now = time.mktime((2008, 8, 22, 11 ,17, -1, -1, -1, -1))
>>> tomorrow = time.mktime((2008, 8, 23, 11 ,17, -1, -1, -1, -1))
>>> tomorrow - now
86400.0
这是你所期望的。 我猜? 也许从时代开始就进行了一些时间的修正。 这可能只有几秒钟,就像闰年。 我想我以前听过这样的话,但是不记得究竟是怎么做的和什么时候做的......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.