Home:ALL Converter>Datetime Unix timestamp contains milliseconds

Datetime Unix timestamp contains milliseconds

Ask Time:2013-09-11T00:14:33         Author:Chris Clouten

Json Formatter

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!

Author:Chris Clouten,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/18724037/datetime-unix-timestamp-contains-milliseconds
Jordan :

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\n\nYou've probably gone over that already.\n\nIt should be reasonably easy to slice off the last 3 digits of your timestamps though:\n\ndatetime.fromtimestamp(str(unix_timestamp)[0:-3])\n\n\nYou might also wish to do some string length checking to verify that they are 13 digits long instead of just 10 though:\n\nif len(unix_timestamp) == 13:\n unix_timestamp = float(str(unix_timestamp)[0:-3])\n\ndatetime.fromtimestamp(unix_timestamp)\n\n\nBy the way, on some systems, timestamps must be between 1970 - 2038. That could also cause a ValueError.\n\nIf you wish to keep milliseconds, you can store them like this:\n\nmilliseconds = 0\nif len(unix_timestamp) == 13:\n milliseconds = int(unix_timestamp[-3:])\n unix_timestamp = float(unix_timestamp[0:-3])\n\nthe_date = datetime.fromtimestamp(unix_timestamp)\nthe_date += timedelta(milliseconds=milliseconds)\n",
2013-09-10T16:18:13
Chronial :

The fromtimestamp method expects a unix timestamp and that has a resolution of seconds. You will have to convert your time in two steps:\n\nmytime = datetime.fromtimestamp(timestamp/1000)\n .replace(microsecond = (timestamp % 1000) * 1000)\n",
2013-09-10T16:21:52
Afroz Alam :

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:\n\ndatetime.datetime.fromtimestamp(float(str(timestamp)[0:-3]))\n",
2015-06-03T11:12:23
chamal sapumohotti :

Simply divide the time stamp value by 1000.\n\ndatetime.fromtimestamp(unix_timestamp/1000.0)\n",
2015-09-07T08:08:40
yy