Python fromtimestamp OSError

If you get this error and you’re not using an obviously wrong timestamp, check your units.

fromtimestamp expects a timestamp in seconds, whereas it’s quite common to get timetstamps in milliseconds (e.g. I found this when trying to parse a timestamp produced from Moment.js in a calendar widget).

Take the timestamp 1523443804214 – it’s 11th April 2018, about 15 minutes before I made this post. According to Epoch Converter, no problem, but note: “Assuming that this timestamp is in milliseconds:”.

In Python this returns an OSError:

In [15]: datetime.fromtimestamp(1523443804214.0)
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-15-0c8efd251031> in <module>()
----> 1 datetime.fromtimestamp(1523443804214.0)

However if we divide by a thousand:

In [17]: datetime.fromtimestamp(1523443804.214)
Out[17]: datetime.datetime(2018, 4, 11, 11, 50, 4, 214000)

the result is what we expect.

Leave a Comment