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

纳秒格式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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:15:03