JavaScript timestamp to Python datetime conversion
Your current method is correct, dividing by 1000 is necessary because your JavaScript returns the timestamp in milliseconds, and datetime.datetime.fromtimestamp()
expects a timestamp in seconds.
To preserve the millisecond accuracy you can divide by 1000.0
, so you are using float division instead of integer division:
>>> dt = datetime.datetime.fromtimestamp(jsts/1000.0)>>> dtdatetime.datetime(2012, 4, 23, 11, 30, 4, 950000)
I've had the same issue, thanks to @andrew-clark for the answer, i've build a small example to handle both cases:
try: # when timestamp is in seconds date = datetime.fromtimestamp(timestamp) except (ValueError): # when timestamp is in miliseconds date = datetime.fromtimestamp(timestamp / 1000)
The way you do it is the correct way, because js includes milliseconds in the date/time. Python (and PHP) as far as I know, don't.For more precision you could use /1000.0
.