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

Django自定义命令中fromtimestamp转换时间戳报OSError如何解决

报错根因
  • Python标准库datetime.fromtimestamp() 仅支持传入秒级单位的Unix时间戳,你调用的贵金属行情接口返回的timestamp为13位毫秒级时间戳,数值远超出方法可接受的有效范围,因此抛出OSError: [Errno 22] Invalid argument错误。
  • 若接口返回的timestamp为字符串格式而非数值格式,也会触发同类参数非法报错。
修复方案

先将毫秒级时间戳除以1000转换为秒级,可选增加类型转换兼容接口返回的字符串类型时间戳,修改后的代码如下:

class Command(BaseCommand):
    def handle(self, *args , **options):
        r = requests.get('https://api.metals.live/v1/spot/silver').json()
        price = r[0]['price']
        # 先转数值类型,再从毫秒转秒级
        timest = int(r[0]['timestamp'])
        timest_sec = timest / 1000
        timest_conv = datetime.fromtimestamp(timest_sec)
        print(price, timest, timest_conv )

        return

内容的提问来源于stack exchange,提问作者hebel.dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:54:01