python - 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
解决方案
假设-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 的问题,但我无法确定。所以如果它仍然存在,也许在这里问。
推荐阅读
- sql - 高效地处理和更新 SQL 中的每一行
- excel - ADODB.Recordset 中小时 >24 时 AVG() 时间的错误结果
- function - 如何获取 Azure FunctionApp 绑定的返回绑定属性
- php - 由于 CORS 错误,Jquery ajax 请求不起作用
- weblogic - 我可以在 weblogic 服务器上终止 close_wait 连接吗
- python - 是否有任何选项可以避免在 AWS API 网关中为 lambda 函数创建更多端点
- ios - 从具有 HH:mm 时间格式的字符串中获取日期在 swift 中不适用于日语和地区
- javascript - 长度函数抛出未捕获的错误
- google-visualization - 我正在尝试创建一个类似于序列图的图表,它会以折线图的形式向我显示多个航班的着陆预测和实际时间
- sql - 我该如何解决这个问题并获得更好的性能