JavaScript timestamp to Python datetime conversion

前端 未结 3 2071
滥情空心
滥情空心 2020-12-03 00:29

To get timestamp in JavaScript we use

var ts = new Date().getTime()

What is the proper way to convert it to a Python datetime

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 01:08

    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)
    

提交回复
热议问题