Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime Unix timestamp contains milliseconds

I have a list of unix timestamps that all contain milliseconds -- they are 13 digits long. When I run the timestamp through datetime.fromtimestamp(unix_timestamp) it returns a ValueError: Year Out of Range. When I cut the last three digits off the timestamp and run it through the same format converter, it's works perfectly. Is it possible to run the Unix timestamp that includes milliseconds through the fromtimestamp method of datetime without raising a ValueError? I was looking at the documentation and it didn't say anything about specifying milliseconds.

Any help would be awesome!

like image 782
Chris Clouten Avatar asked Sep 10 '13 16:09

Chris Clouten


1 Answers

From the documentation, you can see that timestamps in Python are expected to be calculated in seconds, not milliseconds: http://docs.python.org/2/library/time.html#time.time

You've probably gone over that already.

It should be reasonably easy to slice off the last 3 digits of your timestamps though:

datetime.fromtimestamp(str(unix_timestamp)[0:-3])

You might also wish to do some string length checking to verify that they are 13 digits long instead of just 10 though:

if len(unix_timestamp) == 13:
    unix_timestamp = float(str(unix_timestamp)[0:-3])

datetime.fromtimestamp(unix_timestamp)

By the way, on some systems, timestamps must be between 1970 - 2038. That could also cause a ValueError.

If you wish to keep milliseconds, you can store them like this:

milliseconds = 0
if len(unix_timestamp) == 13:
    milliseconds = int(unix_timestamp[-3:])
    unix_timestamp = float(unix_timestamp[0:-3])

the_date = datetime.fromtimestamp(unix_timestamp)
the_date += timedelta(milliseconds=milliseconds)
like image 146
Jordan Avatar answered Oct 01 '22 07:10

Jordan