python3 fromtimestamp生成操作错误

2024-06-01 14:04:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我们在现场遇到了一个有趣的mtime问题。我正计划提交一份bug报告,但想从外部了解情况

存储在windows服务器上的文件的最后修改日期为“1/1/4501”(即4501年)os.path.getmtime()返回一个有效的时间戳,但是当我们试图将它传递回datetime.datetime.fromtimestamp()时,我们得到一个OSError

关于这一问题,有几次讨论,例如:Python fromtimestamp OSError。然而,在我们可以找到的大多数情况下,OP处理的制造日期显然超出了平台支持的历元范围。当日期超过Windows上的历元支持时生成OSError与python文档一致

在我们的例子中,日期显然得到了Windows的支持,文件系统中的存储就证明了这一点。此外,我们可以使用cygwintouch实用程序再现这种情况

>>> import os, datetime
>>> os.system('touch -d "4501-01-01" file.txt')
>>> t = os.path.getmtime('file.txt')
>>> datetime.datetime.fromtimestamp(t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

有趣的是,我们可以参照历元手动转换它

>>> datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=t)
datetime.datetime(4501, 1, 1, 5, 0)

我们在运行Python3.8.1的测试中使用了Windows10Pro


Tags: pathtxtdatetimeoswindows情况现场bug
1条回答
网友
1楼 · 发布于 2024-06-01 14:04:14

好的,这不是一个bug,它是平台的localtime()/gmtime()的一个文档限制。虽然datetime类本身可以处理任意日期,但对timestamp的任何引用都需要通过平台的localtime系统。就我而言,它是Windows1064位

根据文件:https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/localtime-s-localtime32-s-localtime64-s?view=vs-2019

_localtime64_s, which uses the __time64_t structure, allows dates to be expressed up through 23:59:59, January 18, 3001, coordinated universal time (UTC)

传入大于3001年的值会导致localtime64_s返回EINVAL。根据python文档:

This may raise OverflowError, if the timestamp is out of the range of values supported by the platform C localtime() function, and OSError on localtime() failure.

我们现在看到的是后者

相关问题 更多 >