Python OverflowError creating date from timestamp in 32bit system

做~自己de王妃 提交于 2021-01-07 01:29:06

问题


So I am trying to do a simple conversion of a timestamp to date using python builtin datetime module in RaspberryPi4 running Debian Buster.

The conversion works fine in my laptop (64bit Debian) but trows a OverflowError in Debian. The 2 examples follow.

Anyone knows of a simple workaround this issue? Thank you!

In 64bit Debian system:

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

In RasbberryPi (32bit) Raspbian system:

$ 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

回答1:


assuming -11486707200 is seconds since the epoch (Unix time), you could try to add it as a timedelta to the epoch;

from datetime import datetime, timedelta, timezone

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

This works when I test on Python 3.7.9 32 bit. Note that the Raspberry Pi4 CPU has a 64bit architecture, so it's not a "32bit system" in that sense. Not sure if this is an issue of the Pi but I can't test to make sure. So if it persists, maybe ask here.



来源:https://stackoverflow.com/questions/65481616/python-overflowerror-creating-date-from-timestamp-in-32bit-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!