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

pandas使用pd.to_datetime转换公元1年时间戳报错如何解决?

解决pandas转换公元1年时间戳报错、无法正常做索引的问题

报错原因

pandas默认使用datetime64[ns](纳秒精度)存储时间,该类型仅支持1677-09-21到2262-04-11范围内的时间,公元1年的时间超出了这个范围,所以会触发OutOfBoundsDatetime报错。你之前用apply转成Python原生datetime对象后,pandas会将其识别为object类型,因此无法支持时间索引的相关操作。

解决方案

方案1:使用非纳秒精度的datetime64类型(推荐)

降低时间存储精度后,datetime64的支持范围会大幅扩大,比如datetime64[ms](毫秒精度)可覆盖公元前29万年到公元29万年的时间,完全满足你的需求:

import pandas as pd

# 单值转换
pd.to_datetime('15-Jan-0001 00:00:00', format='%d-%b-%Y %H:%M:%S', dtype='datetime64[ms]')

# 批量转换序列
time_series = pd.Series(['15-Jan-0001 00:00:00', '01-Mar-0010 12:30:00'])
converted_series = pd.to_datetime(time_series, format='%d-%b-%Y %H:%M:%S', dtype='datetime64[ms]')

转换后的数据类型为datetime64[ms],设为索引后可正常使用.loc进行时间查询、切片操作。

方案2:使用PeriodIndex(兼容低版本pandas)

如果你的pandas版本低于2.0,对非纳秒精度的datetime支持不完善,可以用固定精度的Period类型存储时间:

import pandas as pd
import datetime

time_series = pd.Series(['15-Jan-0001 00:00:00', '01-Mar-0010 12:30:00'])
# freq参数根据你的时间精度调整,按天用'D'、按小时用'H'、按分钟用'T'
converted_series = pd.PeriodIndex(
    time_series.apply(lambda x: datetime.datetime.strptime(x, '%d-%b-%Y %H:%M:%S')),
    freq='H'
)

Period类型作为索引时,也完全支持.loc的各类时间操作。

注意事项

  • 优先选择和原始数据匹配的最低精度,既能扩大时间支持范围,也不会浪费存储空间
  • 如需使用方案1,建议升级到pandas 2.0及以上稳定版本,避免出现兼容性问题

内容的提问来源于stack exchange,提问作者K. Shores

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:18:01