Search code examples
pythondatetimeraspberry-piraspbian

Python OverflowError creating date from timestamp in 32bit system


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

Solution

  • 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.