57

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?

Llanilek
  • 3,386
  • 5
  • 39
  • 65
  • 5
    See [this question](http://stackoverflow.com/questions/10286224/javascript-timestamp-to-python-datetime-conversion). Are you perhaps not converting from milliseconds to seconds? – sschilli Jul 21 '15 at 19:45
  • Are you sure that was the exact value that was working 3 months ago? even this - `f = 143750677995.0` (your number divided by 10) lands me in the year 6525 . – Anand S Kumar Jul 21 '15 at 19:48
  • samalamma708: you might want to put that as the answer, seems that was the issue. – Llanilek Jul 21 '15 at 19:49

1 Answers1

133

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.

In Python 2, if you want to preserve millisecond precision, instead divide by 1000.0. In Python 3, you will preserve it anyway dividing by 1000 or 1000.0.

Nuno André
  • 4,739
  • 1
  • 33
  • 46
sschilli
  • 2,021
  • 1
  • 13
  • 33