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

如何将自公元前1年1月1日起的天数转为Pandas datetime格式?

解决从公元前1年1月1日起的天数转Pandas datetime的问题

问题核心在于Python标准库的datetime对象不支持公元1年之前的日期,你尝试的origin=datetime.datetime(-1,1,1)会直接报错,因为它的范围仅限公元1年及以后。要处理这种从公元前1年起始的天数转换,需要借助numpy的datetime64类型(它支持更早的时间范围)。

单值转换示例

import pandas as pd
import numpy as np

# 定义起始点:公元前1年1月1日,numpy用'-0001'表示公元前1年
origin = np.datetime64('-0001-01-01')
# 你的示例天数
days = 736698.0
# 计算目标日期
target_date = origin + np.timedelta64(int(days), 'D')
# 转为Pandas datetime格式
pd_date = pd.to_datetime(target_date)
print(pd_date)  # 输出: 2017-01-04 00:00:00

批量转换示例

如果是Pandas Series格式的批量数据,可以这样处理:

import pandas as pd
import numpy as np

# 示例批量天数数据
days_series = pd.Series([736698.0, 735000.0, 737000.0])
origin = np.datetime64('-0001-01-01')

# 批量转换
date_series = pd.to_datetime(
    origin + days_series.astype(int).apply(np.timedelta64, args=('D',))
)
print(date_series)

原理说明

  • numpy.datetime64('-0001-01-01')正确表示了公元前1年1月1日(无公元0年,公元前1年之后直接是公元1年)。
  • 将天数转为整数后,通过np.timedelta64转为日期间隔,与起始日期相加得到目标日期,最后再转为Pandas的datetime类型即可。

内容的提问来源于stack exchange,提问作者geofisue

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 16:20:12