Python日期时间转换的JavaScript时间戳 [英] JavaScript timestamp to Python datetime conversion

查看:173
本文介绍了Python日期时间转换的JavaScript时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

To get timestamp in JavaScript we use

var ts = new Date().getTime()

将它转换为Python的正确方法是什么 datetime 所以我使用以下代码

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)

我将时间戳除以1000因为我得到错误

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以毫秒为单位返回时间戳,所以除以1000是必要的,并且 datetime.datetime.fromtimestamp()期望以秒为单位的时间戳。

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.0 ,因此您使用浮动除法而不是整数除法:

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)

这篇关于Python日期时间转换的JavaScript时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆