JavaScript timestamp to Python datetime conversion

题意:JavaScript 时间戳转换为 Python 日期时间

问题背景:

To get timestamp in JavaScript we use

在 JavaScript 中获取时间戳,我们使用

var ts = new Date().getTime()

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

将其转换为 Python 的 datetime 的正确方法是什么?到目前为止,我使用以下代码

>>> 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

我将时间戳除以1000,因为我遇到了类似这样的错误:

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

问题解决:

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.

你当前的方法是正确的,除以1000是必要的,因为你的JavaScript返回的时间戳是以毫秒为单位的,而datetime.datetime.fromtimestamp()函数期望的时间戳是以秒为单位的。

To preserve the millisecond accuracy you can divide by 1000.0, so you are using float division instead of integer division:

为了保持毫秒级的精度,你可以除以1000.0,这样你就是在使用浮点数除法而不是整数除法:

>>> dt = datetime.datetime.fromtimestamp(jsts/1000.0)
>>> dt
datetime.datetime(2012, 4, 23, 11, 30, 4, 950000)

猜你喜欢

转载自blog.csdn.net/suiusoar/article/details/143507948