我这样做:
timestamp=long('1455873250789')
print(timestamp)
d=datetime.datetime(timestamp)
我明白了:
1455873250789
Traceback (most recent call last):
File ".../pycharm-5.0.4/helpers/pydev/pydevd.py", line 2411, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File ".../pycharm-5.0.4/helpers/pydev/pydevd.py", line 1802, in run
launch(file, globals, locals) # execute the script
File "....py", line ..., in <module>
d=datetime.datetime(timestamp)
OverflowError: signed integer is greater than maximum
为什么?
答案 0 :(得分:6)
使用datetime.datetime.fromtimestamp
:
>>> datetime.datetime.fromtimestamp(timestamp / 1000.0)
datetime.datetime(2016, 2, 19, 18, 14, 10, 789000)
注意:timestamp
在传递给方法之前应该除以1000,因为给定时间戳的单位是毫秒,而fromtimestamp
接受秒(这是官方的UNIX时间戳)。
答案 1 :(得分:0)
import datetime
timestamp = int('1455873250789'[:-3])
print(datetime.datetime.fromtimestamp(timestamp))
这将从时间戳字符串中删除最后三个字符,实质上是将时间戳从毫秒转换为秒。使用fromtimestamp()
,您可以将Unix时间戳(以秒为单位)转换为datetime
对象。