You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python转换JSON毫秒时间戳报错求助:OSError: [Errno 22]

问题解决:毫秒级时间戳转换错误

你的报错原因很明确:JSON接口返回的是毫秒级时间戳(13位数字),但Python的time模块函数(ctime、localtime等)只支持秒级时间戳(10位数字)。直接传入毫秒数会超出函数的有效时间范围,导致OSError。

修正方案

把毫秒级时间戳除以1000,转换成秒级后再处理:

用time模块修正代码

import time

# 先将毫秒时间戳转为秒级
timestamp_seconds = int("1667300455000") // 1000

# 正常转换并输出
print(time.ctime(timestamp_seconds))
print(time.strftime("%D %H:%M", time.localtime(timestamp_seconds)))

更直观的datetime模块方案

如果觉得time模块不够灵活,也可以用datetime模块直接处理:

from datetime import datetime

timestamp_ms = int("1667300455000")
# 直接将毫秒时间戳转为datetime对象
dt = datetime.fromtimestamp(timestamp_ms / 1000)
# 按需求格式化输出
print(dt.strftime("%D %H:%M"))

运行修正后的代码,就能得到正确的日期:11/01/22 15:00(对应时间戳1667300455秒的本地时间)。

内容的提问来源于stack exchange,提问作者raulinho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:10:55