Why is Datetime's `.timestamp()` method returning `OSError: [Errno 22] Invalid argument`?

Why is Datetime's `.timestamp()` method returning `OSError: [Errno 22] Invalid argument`?

我在我的代码中两次使用 .timestamp() 函数,将日期时间对象转换为纪元时间。对 .timestamp() 的第一次调用如下所示:

import datetime    
origin_epoch = origin.timestamp()

变量originorigin_epoch的内容是:

同时,如果我尝试在我的代码中的其他地方调用相同的方法

import datetime
print(datetime.datetime(1900, 1, 1, 19, 6, 28).timestamp())

然后我得到以下错误:OSError: [Errno 22] Invalid argument这是为什么?

编辑: 这个错误发生在 Windows 10.

1900 年早于 the UNIX epoch, which was in 1970, so the number of seconds returned by timestamp must be negative. To be precise, ,但显然,您的情况并非如此。看起来您的 OS 只是将 UNIX 纪元开始之前的日期视为错误。

我在 mac 上工作正常OS,不过:

>>> datetime.datetime(1900, 1, 1, 19, 6, 28).timestamp()
-2208929029.0

这似乎是 known issue,据称已修复,但我尚未检查。在我的 Windows(Windows 10,GMT+2)1970-01-02 02:00:00 之前或 3001-01-19 07:59:59 之后的任何日期都会给出 OSError 当调用 timestamp() 时。

然而,这不会发生在偏移感知日期时间上,相反,它们被计算为(来自 docs):

(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()

事实上,对于原始偏移日期时间,可以简单地使用:

(dt - datetime(1970, 1, 1)).total_seconds()