Python - unix timestamp 时间戳转换错误

发布时间 2023-09-13 11:32:17作者: 猫叔Vincent

用python的时间转换函数,结果报错。想着这么基础的怎么会报错呢。

from datetime import datetime

# timestamp is number of seconds since 1970-01-01 
timestamp = 1545730073

# convert the timestamp to a datetime object in the local timezone
dt_object = datetime.fromtimestamp(timestamp)

# print the datetime object and its type
print("dt_object =", dt_object)

执行到第九行爆OSError [Errno22] Invalid Argument

原因是Windows下是毫秒级的时间戳,需要除以1000才可以转成秒级。

所以上面只要改一下即可

dt_object = datetime.fromtimestamp(timestamp / 1000)



初学python,慢慢积累。