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:
- passingformatif your strings have a consistent format;
- passingformat='ISO8601'if your strings are all ISO8601 but not necessarily in exactly the same format;
- passingformat='mixed', and the format will be inferred for each element individually. You might want to usedayfirstalongside 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
相关产品推荐
相关产品推荐

