Skip to main content
 首页 » 编程设计

python之time.mktime 不接受 1900 年之前的年份

2025年05月04日16hnrainll

在 python 2.7 time.mktime 中不接受 1900 之前的年份,这很奇怪。

>>> time.mktime(time.strptime("1/1/1899","%d/%m/%Y")) 
Traceback (most recent call last): 
  File "<pyshell#293>", line 1, in <module> 
    time.mktime(time.strptime("1/1/1899","%d/%m/%Y")) 
ValueError: year out of range 

但是 calendar.timegm 可以做所有的值。

>>> calendar.timegm(time.strptime("1/1/1899","%d/%m/%Y")) 
-2240524800 
 
>>> calendar.timegm(time.strptime("1/1/0001","%d/%m/%Y")) 
-62135596800 

这是预期的行为吗?这对我来说有点奇怪。似乎不可能溢出 double 仅仅 -71 年。

请您参考如下方法:

这是预期的行为。

  • 第一个记录在 Python 2.7 docs under Year 2000 (Y2K) issues 中.上面写着

    Values 100–1899 are always illegal.

    Python 3 支持这些日期,因此没有此类限制 ( docs )。

  • 具有负日期的第二个点也是预期的。日期在 seconds since the epoch 中(自 1970 年 1 月 1 日 00:00:00 UTC 以来的秒数)。因此在此之前的日期存储为负数。