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

为何Pandas的to_datetime转换部分日期列表报错,替换日期后却正常?

问题描述

我有一个返回节假日列表的函数,列表内容为:

['30 May 2024','1 May 2024', '29 Aug 2024', '14 Aug 2024', '19 May 2024'] 

执行以下代码时:

print(pd.to_datetime(['30 May 2024','1 May 2024', '29 Aug 2024', '14 Aug 2024', '19 May 2024']))

触发ValueError错误,提示:

ValueError: time data "29 Aug 2024" doesn't match format "%d %B %Y", at position 2. You might want to try:
    - passing `format` if your strings have a consistent format;
    - passing `format='ISO8601'` if your strings are all ISO8601 but not necessarily in exactly the same format;
    - passing `format='mixed'`, and the format will be inferred for each element individually. You might want to use `dayfirst` alongside this.

但将列表第一个元素替换为'30 Dec 2024'后,执行相同的pd.to_datetime转换代码却能正常得到:

DatetimeIndex(['2024-12-30', '2024-05-01', '2024-08-29', '2024-08-14',
               '2024-05-19'],
          dtype='datetime64[ns]', freq=None)

请问忽略了什么细节?

关键细节解析

核心问题出在pandas推断日期格式的逻辑上:

  • 未指定format参数时,pd.to_datetime会优先用列表前几个元素(通常是第一个)推断日期格式。
  • 第一个例子里,第一个元素是'30 May 2024',May是月份的全称,pandas因此推断格式为%d %B %Y(日+全称月+年)。但后面的Aug是月份的缩写,和%B(匹配全称)不兼容,触发格式不匹配错误。
  • 换成'30 Dec 2024'后,Dec是月份的缩写,pandas推断格式为%d %b %Y(日+缩写月+年)。而May的缩写和全称完全一致,能匹配%b,后面的Aug也是标准缩写,因此所有元素都能转换成功。
解决办法

如果日期字符串混用月份全称和缩写,或不确定格式一致性,直接指定format='mixed'让pandas逐个元素推断格式即可:

print(pd.to_datetime(holiday_list, format='mixed', dayfirst=True))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 20:57:36