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

Pandas.to_datetime转换0001年日期报错,如何解决?

解决Pandas解析公元1年日期的OutOfBoundsDatetime错误

这个问题的核心原因很明确:Pandas默认使用的datetime64[ns]数据类型有严格的时间范围限制——它只能表示从1677-09-21 00:12:43.145225到2262-04-11 23:47:16.854775807之间的日期,公元1年的日期远远超出了这个范围,所以会触发OutOfBoundsDatetime错误。

下面是几个可行的解决办法,按推荐程度排序:

1. 使用Python引擎解析日期

Pandas的pd.to_datetime提供了engine='python'参数,它会调用Python标准库的datetime模块(依赖dateutil)来解析日期,支持更早的时间范围。直接修改你的代码即可:

import pandas as pd
df = pd.read_csv(file)  # 注意你原代码里的`load_csv`是笔误,正确方法是`read_csv`
df['datetime'] = pd.to_datetime(df['datetime'], engine='python')

解析完成后,datetime列的类型会变成object(存储Python原生的datetime.datetime对象),这样就能正常处理公元1年的日期了,同时保留完整的时分秒信息。

2. 利用拆分好的年月日列构造日期

你的CSV里已经有year、month、day列,直接用这些列构造日期会更可靠,避免字符串解析可能出现的格式问题,同样搭配engine='python':

df['datetime'] = pd.to_datetime(df[['year', 'month', 'day']], engine='python')

如果需要保留时分秒,可以手动补充:

df['datetime'] = pd.to_datetime(df[['year', 'month', 'day']], engine='python') + pd.to_timedelta('00:00:00')

3. 注意事项

  • 使用object类型的datetime列时,部分Pandas时间序列专属函数(比如resample、rolling)的性能可能会比datetime64[ns]稍差,但对于包含极早日期的数据集来说,这是必要的折中。
  • 确保你的环境安装了python-dateutil库(Pandas通常会自动依赖它,如果没有的话可以用pip install python-dateutil安装)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:27:13