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 Win7 64-bit and python 3.5.1. Here's code that produces the error.
>>> import datetime >>> import pytz >>> datetime.datetime.fromtimestamp(-43200, pytz.utc) datetime.datetime(1969, 12, 31, 12, 0, tzinfo=<UTC>) >>> datetime.datetime.fromtimestamp(-43201, pytz.utc) Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 22] Invalid argument
The sample uses pytz to simplify timezone information, but the error also occurs without it.
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.
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 have a negative timestamp t
on Windows and are encountering this error, here is a workaround:
from datetime import datetime, timedelta datetime.fromtimestamp(0) + timedelta(seconds=t) # localtime datetime.utcfromtimestamp(0) + timedelta(seconds=t) # utc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With