首页 > 解决方案 > Python OverflowError 从 32 位系统中的时间戳创建日期

问题描述

所以我试图在运行 Debian Buster 的 RaspberryPi4 中使用 python 内置日期时间模块将时间戳简单转换为日期。

转换在我的笔记本电脑(64 位 Debian)中运行良好,但在 Debian 中引发了溢出错误。以下是 2 个示例。

有人知道这个问题的简单解决方法吗?谢谢!

在 64 位 Debian 系统中:

$ python3 -c "from datetime import datetime; d=datetime.fromtimestamp(int("-11486707200")); print(d.year)"
1606

在 RasbberryPi (32bit) Raspbian 系统中:

$ python3 -c "from datetime import datetime; d=datetime.fromtimestamp(int("-11486707200")); print(d.year)"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
OverflowError: timestamp out of range for platform time_t

标签: pythondatetimeraspberry-piraspbian

解决方案


假设-11486707200是自纪元(Unix 时间)以来的秒数,您可以尝试将其作为 a 添加timedelta到纪元;

from datetime import datetime, timedelta, timezone

d = datetime.fromtimestamp(0, tz=timezone.utc) + timedelta(seconds=-11486707200)
print(d.year)
>>> 1606

这在我测试 Python 3.7.9 32 位时有效。请注意,Raspberry Pi4 CPU 具有 64 位架构,因此在这个意义上它不是“32 位系统”。不确定这是否是 Pi 的问题,但我无法确定。所以如果它仍然存在,也许在这里问。


推荐阅读