纳秒格式Timestamp转换为datetime时执行代码报错怎么解决
纳秒时间戳转datetime报错修复方案
错误原因
datetime.datetime.fromtimestamp() 方法默认接收秒级Unix时间戳,你传入的是纳秒级时间戳,数值远超出方法支持的合法范围,因此触发报错。
修复代码
方案1:纳秒转秒后转换(兼容所有Python版本)
import datetime example_timestamp = '1629617204525776950' example_timestamp = int(example_timestamp) # 纳秒转秒,保留小数部分以保证微秒级精度 timestamp_in_second = example_timestamp / 10**9 timestamp_to_date_time = datetime.datetime.fromtimestamp(timestamp_in_second).strftime('%Y-%m-%d %H:%M:%S,%f') # 输出示例:2021-08-22 15:26:44,525777
如果需要获取UTC时区的时间,把fromtimestamp替换为utcfromtimestamp即可。
方案2:通过时间差计算(避免时区自动转换)
如果你需要严格使用UTC纪元计算、不触发本地时区转换,可以用时间差累加实现:
import datetime example_timestamp = '1629617204525776950' example_timestamp = int(example_timestamp) # 纳秒转微秒(datetime最多支持微秒精度) timestamp_in_us = example_timestamp // 1000 dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=timestamp_in_us) timestamp_to_date_time = dt.strftime('%Y-%m-%d %H:%M:%S,%f')
内容的提问来源于stack exchange,提问作者BABZI
相关产品推荐
相关产品推荐

