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

如何在Pandas中将不同格式日期字符串转为统一DD-MM-YYYY格式日期对象?

解决混合日期格式转换问题

这个问题我之前也碰到过,核心原因是你的数据里同时存在YYYY-MM-DD和DD-MM-YYYY两种日期格式,但你指定了单一的%d-%m-%Y格式去解析,导致像1899-12-31这种符合YYYY-MM-DD格式的数据无法匹配,从而抛出错误。下面给你几个可行的解决方案:

方法一:让Pandas自动推断格式(简单高效)

Pandas的pd.to_datetime本身具备自动识别多种日期格式的能力,你可以去掉format参数,让它自动解析所有格式,同时用errors='coerce'把无法识别的无效日期转为NaT(避免报错中断):

import pandas as pd

# 先将混合格式的字符串转为datetime对象
df['accepted_date'] = pd.to_datetime(df['accepted_date'], errors='coerce')

# 如果需要将datetime对象转为DD-MM-YYYY格式的字符串(可选)
df['accepted_date'] = df['accepted_date'].dt.strftime('%d-%m-%Y')
  • 注意:如果选择保留datetime对象(不执行第二行),Pandas内部存储的是标准日期格式,你可以通过设置显示选项让它默认显示为DD-MM-YYYY:
    pd.options.display.date_format = '%d-%m-%Y'
    

方法二:手动匹配格式(精准可控)

如果担心自动推断出错,你可以用正则表达式分别匹配两种格式的行,再分别解析:

import pandas as pd

# 匹配YYYY-MM-DD格式的行
mask_ymd = df['accepted_date'].str.match(r'^\d{4}-\d{2}-\d{2}$')
df.loc[mask_ymd, 'accepted_date'] = pd.to_datetime(df.loc[mask_ymd, 'accepted_date'], format='%Y-%m-%d')

# 匹配DD-MM-YYYY格式的行
mask_dmy = df['accepted_date'].str.match(r'^\d{2}-\d{2}-\d{4}$')
df.loc[mask_dmy, 'accepted_date'] = pd.to_datetime(df.loc[mask_dmy, 'accepted_date'], format='%d-%m-%Y')

# 统一转为DD-MM-YYYY格式的字符串(可选)
df['accepted_date'] = df['accepted_date'].dt.strftime('%d-%m-%Y')

这种方法更灵活,适合数据格式复杂、需要精准控制的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:29:57