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

Jupyter Notebook中pd.to_datetime解析多格式日期报错的解决方法

解决pandas多格式日期解析报错问题

执行以下代码尝试统一解析不同格式的日期时触发ValueError:

import pandas as pd
dates=['2017-01-05','Jan 5,2017','20170105']
pd.to_datetime(dates)

报错核心信息:

ValueError: time data "Jan 5,2017" doesn't match format "%Y-%m-%d", at position 1. 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.


解决方法

直接在pd.to_datetime()中添加format='mixed'参数,让pandas自动推断每个日期字符串的格式:

import pandas as pd
dates=['2017-01-05','Jan 5,2017','20170105']
# 解析为datetime类型
parsed_dates = pd.to_datetime(dates, format='mixed')
# 转换为统一的YYYY/mm/dd字符串格式
formatted_dates = parsed_dates.strftime('%Y/%m/%d')

print(formatted_dates)

输出结果:

['2017/01/05' '2017/01/05' '2017/01/05']

额外注意

如果存在日/月顺序混淆的风险(比如部分日期格式是日在前),可以显式设置dayfirst参数控制解析逻辑:

parsed_dates = pd.to_datetime(dates, format='mixed', dayfirst=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 19:46:04