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

解析多格式日期列遇错误:pandas转换datetime失败

解决pandas中混合格式日期(dd/mm/yy和dd/mm/yyyy)的类型转换问题

问题说明

DataFrame内同时存在dd/mm/yy和dd/mm/yyyy两种格式的日期,使用pd.to_datetime转换时触发如下错误:

ValueError: time data "02/11/21" doesn't match format "%m/%d/%Y", at position 129. 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.

若执行以下代码:

df['date_column'] = pd.to_datetime(df['date_column'], format='%m/%d/%Y', errors='coerce')

会导致多数日期值被转换为NaT(缺失时间值)。

解决方案

方法1:用format='mixed'配合dayfirst=True

你的日期是日在前、月在后的格式,且存在两位/四位年份混合的情况,直接让pandas自动推断格式,同时明确日在前的规则:

df['date_column'] = pd.to_datetime(df['date_column'], format='mixed', dayfirst=True)

方法2:省略format,直接指定dayfirst=True

如果日期格式统一为dd/mm/yy或dd/mm/yyyy,可以依赖pandas的自动推断,只需明确日在前:

df['date_column'] = pd.to_datetime(df['date_column'], dayfirst=True)

方法3:分格式逐步转换(应对复杂场景)

若自动推断失效,可手动针对两种格式分别转换,再合并结果:

# 先转换dd/mm/yyyy格式的日期
df['date_column'] = pd.to_datetime(df['date_column'], format='%d/%m/%Y', errors='coerce')
# 对未转换成功的NaT值,用dd/mm/yy格式重新转换
mask = df['date_column'].isna()
df.loc[mask, 'date_column'] = pd.to_datetime(df.loc[mask, 'date_column'], format='%d/%m/%y', errors='coerce')

关键原因

之前使用format='%m/%d/%Y'是错误的——该格式代表月/日/年,和你的日/月/年格式完全不匹配,因此大部分数据无法被正确解析,最终变成NaT。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:25:58