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
相关产品推荐
相关产品推荐

