【问题标题】:Why is Datetime's `.timestamp()` method returning `OSError: [Errno 22] Invalid argument`?为什么 Datetime 的`.timestamp()` 方法返回`OSError: [Errno 22] Invalid argument`?
【发布时间】:2020-03-30 16:05:31
【问题描述】:

我在代码中两次使用.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 上。

【问题讨论】:

    标签: python python-3.x datetime epoch


    【解决方案1】:

    1900 年早于 the UNIX epoch 的开始,即 1970 年,因此 timestamp 返回的秒数必须为负数。准确地说,@ 987654322@,但显然不是你的情况。看起来您的操作系统只是将 UNIX 纪元开始之前的日期视为错误。

    不过,这在 macOS 上对我来说很好用:

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

    【讨论】:

    • 哇,我永远也猜不到这一点。非常感谢!这很有趣,因为如果您不指定年份,则 datetime 模块中的默认年份是 1900。因此,在 Windows 上,每当您在具有默认年份的 datetime 对象上运行timestamp() 时,程序都会因“Errno”而崩溃22"
    • @David, this question 也可能有帮助
    【解决方案2】:

    这似乎是一个known issue,据说已经修复,但我没有检查。在我的 Windows(Windows 10,GMT+2)上,任何早于 1970-01-02 02:00:00 或晚于 3001-01-19 07:59:59 的日期都会在调用timestamp() 时给出OSError

    但是,这不会发生在可感知偏移量的日期时间中,相反,它们被计算为(来自 docs):

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-06-29
      • 1970-01-01
      • 2021-08-26
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 2018-06-15
      • 1970-01-01
      相关资源
      最近更新 更多