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

Pandas解析CSV日期失败:报错求助及解决方法

解决Pandas转换“日/月/年”格式日期的报错问题

问题背景

尝试将CSV中格式为日/月/年(部分带时间后缀,如13/01/2019 0:00)的VAR1列转换为日期格式,使用代码:

import datetime

df['DATE'] = pd.to_datetime(df['VAR1']).dt.date

执行后触发报错:

ValueError: time data "13/01/2019 0:00" doesn't match format "%m/%d/%Y %H:%M", at position 575. 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.

解决办法

方法1:指定dayfirst=True

告诉Pandas日期字符串的日部分在前,月部分在后,适合统一格式的日期数据:

df['DATE'] = pd.to_datetime(df['VAR1'], dayfirst=True).dt.date

方法2:明确指定格式字符串

如果所有数据的格式完全统一(如日/月/年 时:分),直接指定格式字符串可以提升解析效率:

df['DATE'] = pd.to_datetime(df['VAR1'], format='%d/%m/%Y %H:%M').dt.date

方法3:混合格式场景使用format='mixed'

如果部分数据只有日期(日/月/年),部分带时间,用mixed模式配合dayfirst=True让Pandas自动推断每个元素的格式:

df['DATE'] = pd.to_datetime(df['VAR1'], format='mixed', dayfirst=True).dt.date

报错原因

Pandas默认解析日期时会优先将字符串的第一个数值识别为月份,而13/01/2019中的13超出了月份的合法范围(1-12),因此抛出格式不匹配的错误。通过上述参数指定正确的日期顺序或格式,即可完成解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:52:23