JavaScript timestamp to Python datetime conversion

JavascriptPythonTimestamp

Javascript Problem Overview


To get timestamp in JavaScript we use

var ts = new Date().getTime()

What is the proper way to convert it to a Python datetime so far I use the following code

>>> jsts = 1335205804950
>>> dt = datetime.datetime.fromtimestamp(jsts/1000)
>>> dt
datetime.datetime(2012, 4, 24, 0, 30, 4)

I divide timestamp by 1000 because I get error like

ValueError                                Traceback (most recent call last)
1 d = datetime.datetime.fromtimestamp(a)
ValueError: year is out of range

Sultan.

Javascript Solutions


Solution 1 - Javascript

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)
>>> dt
datetime.datetime(2012, 4, 23, 11, 30, 4, 950000)

Solution 2 - Javascript

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)

Solution 3 - Javascript

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.

Solution 4 - Javascript

For others still getting an error: I had a similar issue but the unix timestamp was in microseconds, i.e. I had to divide the timestamp by 1000000 to get the correct result.

dt = datetime.datetime.fromtimestamp(1502360499615921)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsultanView Question on Stackoverflow
Solution 1 - JavascriptAndrew ClarkView Answer on Stackoverflow
Solution 2 - JavascriptshinyView Answer on Stackoverflow
Solution 3 - Javascriptjadkik94View Answer on Stackoverflow
Solution 4 - JavascriptJuuso NykänenView Answer on Stackoverflow