使用time.mktime的日期/时间转换似乎错误
时间:2020-03-05 18:41:55 来源:igfitidea点击:
>>> 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
应该返回自纪元以来的秒数。由于我给它的时间是午夜,而纪元是午夜,所以结果不应该被一天中的秒数均分吗?
解决方案
回答
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
回答
有趣的。我不知道,但是我确实尝试过:
>>> 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
这是你所期望的。我猜?自该时期以来,也许已经进行了一些时间校正。这可能只有几秒钟,就像a年一样。我想我以前听过类似的话,但是不记得确切的方式和时间了。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
回答
简短答案:由于时区。
大纪元处于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()
函数。
回答
菲尔(Phil)的回答确实解决了这个问题,但我会详细说明。由于该纪元处于UTC中,因此,如果我想将其他时间与该纪元进行比较,则也需要将它们解释为UTC。
>>> calendar.timegm((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 1233360000 >>> 1233360000 / (60*60*24) 14275
通过将时间元组转换为时间戳,将其视为UTC时间,我得到一个数字,该数字可以被一天中的秒数平均整除。
我可以使用它来将日期转换为以天为单位的表示形式,这是我最终追求的。