解析13位Unix时间戳报year out of range如何兼容10位场景?
报错根因
13位Unix时间戳为毫秒精度,数值等于对应秒级时间戳乘以1000,而datetime.fromtimestamp()默认仅接收秒级时间戳作为入参,直接传入13位整数会计算出5万多年后的错误时间,超出Python支持的日期范围。
解决方案
提供两种可选实现,可根据业务场景选择:
方案1:修改时间戳提取函数,输出统一为秒级格式
提取到时间戳后直接做精度归一化,后续所有调用逻辑无需调整:
import re def parse_unixtimestamp(filename): ts_str = re.findall(r'\d{13}|\d{10}', filename)[0] ts_int = int(ts_str) # 13位毫秒转秒级,丢弃毫秒部分 if len(ts_str) == 13: ts_int = ts_int // 1000 return str(ts_int)
方案2:修改日期解析函数,兼容两种精度输入
如果有其他场景也会传入13位时间戳,直接在解析层做兼容通用性更强:
from datetime import datetime # 注意自行导入代码中用到的logger def get_dateparts(in_unixtimestamp): ts = int(in_unixtimestamp) # 10位秒级时间戳最大值为9999999999,对应2286年,超出该值默认按毫秒级处理 if ts > 9999999999: ts = ts // 1000 dt_object = datetime.fromtimestamp(ts) date_string = dt_object.strftime("%Y-%m-%d") year_string = dt_object.strftime("%Y") month_string = dt_object.strftime("%m") day_string = dt_object.strftime("%d") logger.info(f'year_string: {year_string}') result = {"date_string": date_string, "year_string": year_string, "month_string": month_string, "day_string": day_string} return result
如果你的业务需要覆盖2286年之后的10位时间戳场景,可将判断逻辑改为按字符串长度判断避免误判:
def get_dateparts(in_unixtimestamp): ts_str = str(in_unixtimestamp) ts = int(ts_str) if len(ts_str) == 13: ts = ts // 1000 # 后续逻辑和原有代码保持一致
内容的提问来源于stack exchange,提问作者x89
相关产品推荐
相关产品推荐

