从API获取的UNIX时间戳转datetime触发OSError: [Errno 22] Invalid argument
解决OSError: [Errno 22] Invalid argument的时间戳转换问题
嘿,这个报错的根源其实很简单——你手里的是毫秒级的UNIX时间戳,但datetime.fromtimestamp()默认只认秒级的时间戳!
你看,括号里的1516367982230是13位数字,这是精确到毫秒的时间戳;而fromtimestamp()需要的是10位的秒级时间戳。你直接把13位数字传进去,相当于告诉Python要处理一个几千亿年后的时间,这远远超出了Python能识别的时间范围,自然就触发Invalid argument错误了。
修正后的代码
只需要把毫秒时间戳除以1000,转换成秒级的数值再传入就可以了:
import datetime as dt # 假设你的SentDate是字符串格式的"Date(1516367982230)" timestamp_ms = int(SentDate[6:-2]) # 转成秒级时间戳(用浮点数保留毫秒精度) SentDate = dt.datetime.fromtimestamp(timestamp_ms / 1000).strftime('%Y-%m-%d %H:%M:%S')
额外优化:保留毫秒精度
如果想把毫秒也显示出来,可以调整格式化字符串:
SentDate = dt.datetime.fromtimestamp(timestamp_ms / 1000).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] # 输出示例:2018-01-19 12:39:42.230
内容的提问来源于stack exchange,提问作者Henk de Vries




