For some reason when constructing datetimes using fromtimestamp, I get a \"OSError [Errno22] Invalid Argument\" when I use negative times less than -43200 (-12hrs). I am on
If the timestamp is out of the range of values supported by the platform C localtime()
or gmtime()
functions, datetime.fromtimestamp()
may raise an exception like you're seeing.
On Windows platform, this range can sometimes be restricted to years in 1970 through 2038. I have never seen this problem on a Linux system.
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.
A timestamp is the number of seconds since January 1st 1970, and this is always a positive value.
@wim's answer is correct, but anyone else arriving here might be interested in testing it (adjust range if you wish):
import datetime
import platform
print(
"Running on Python ver.{} on {} {}\n" \
.format(
platform.python_version(),
platform.system(),
platform.release()
)
)
for timestamp in range(1, 100000000):
try:
dt = datetime.datetime.fromtimestamp(timestamp)
except:
pass
else:
break
print(
"Smallest accepted Unix timestamp by {}: '{}' ({})" \
.format(platform.system(), timestamp, dt)
)
What I got was:
A:\src\X.utilities>test.py
Running on Python ver.3.6.1 on Windows 7
Smallest accepted Unix timestamp by Windows: '86400' (1970-01-02 02:00:00)
To solve this problem, divide the timestamp value by 1000.
In Windows, the timestamp number is multiplied by a factor of a 1000.