使用time.mktime进行日期/时间转换似乎不正确

4 投票
4 回答
5659 浏览
提问于 2025-04-11 00:14
>>> 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 这个函数应该返回自“纪元”以来的秒数。因为我给它的是午夜的时间,而“纪元”也是在午夜,所以结果不应该能被一天的秒数整除吗?

4 个回答

2

Phil的回答真的解决了问题,但我想再多说一点。因为时间的起点(epoch)是以协调世界时(UTC)为准的,所以如果我想把其他时间和这个起点进行比较,我也需要把这些时间当作UTC来理解。

>>> calendar.timegm((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000
>>> 1233360000 / (60*60*24)
14275

通过把时间元组转换成时间戳,并把它当作UTC时间来处理,我得到的数字可以被一天的秒数整除。

我可以用这个方法把日期转换成距离起点的天数,这正是我最终想要的结果。

3
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.
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233356400.0
>>> (1233378000.0 - 1233356400)/(60*60)
6.0

本地时间……真有意思。

时间元组:

顺便提一下,我们似乎相差6个小时:

8

简单来说:这是因为时区的问题。

时间纪元是以协调世界时(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

你可以看看time.gmtime()这个函数,它是以UTC为基础的。

撰写回答