Datetime Unix timestamp contains milliseconds Datetime Unix timestamp contains milliseconds unix unix

Datetime Unix timestamp contains milliseconds


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 = 0if 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)


The fromtimestamp method expects a unix timestamp and that has a resolution of seconds. You will have to convert your time in two steps:

mytime = datetime.fromtimestamp(timestamp/1000)                 .replace(microsecond = (timestamp % 1000) * 1000)


Explanation by @Jordan is very nice but i think there might be error in parsing which i was facing so i coorected the code as below:

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