JavaScript timestamp to Python datetime conversion(JavaScript 时间戳到 Python 日期时间的转换)
问题描述
要在 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
苏丹.
推荐答案
你当前的方法是正确的,除以 1000 是必要的,因为你的 JavaScript 以毫秒为单位返回时间戳,而 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)
这篇关于JavaScript 时间戳到 Python 日期时间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript 时间戳到 Python 日期时间的转换


基础教程推荐
- 直接将值设置为滑块 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01