Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python datetime fromtimestamp yielding valueerror year out of range [duplicate]

When attempting to convert a float formatted timestamp e.g 1437506779950.0 into a datetime object, I'm getting a ValueError "year is out of range".

This code that I used, was working not 3 months ago. Revisiting it now, strangely is now throwing this error yet nothing in the code base has changed, only the data that is being passed to it, and the only data that has changed there is obviously the timestamp.

>>> f = 1437506779950.0 >>> datetime.datetime.fromtimestamp(float(f)) Traceback (most recent call last):   File "<stdin>", line 1, in <module> ValueError: year is out of range 

I can't understand what would have changed to make this break?

like image 274
Llanilek Avatar asked Jul 21 '15 19:07

Llanilek


People also ask

What is Fromtimestamp in Python?

The fromtimestamp() function is used to return the date corresponding to a specified timestamp. Note: Here the timestamp is ranging from the year 1970 to the year 2038, and this function does not consider leap seconds if any present in the timestamp. This function is a class method.


1 Answers

As noted in the answer for this question, this looks like a unit conversion issue. You have to divide your timestamp by 1000 to convert from milliseconds to seconds.

If you want to preserve millisecond precision, instead divide by 1000.0.

like image 144
sschilli Avatar answered Oct 03 '22 03:10

sschilli