ValueError:日期超出月份范围 [英] ValueError: day is out of range for month

查看:95
本文介绍了ValueError:日期超出月份范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字符串从数据帧转换为日期时间.

I want to convert a string from a dataframe to datetime.

dfx = df.ix[:,'a']
dfx = pd.to_datetime(dfx)

但是会出现以下错误:

ValueError:日期超出月份范围

ValueError: day is out of range for month

任何人都可以帮忙吗?

Can anyone help?

推荐答案

也许可以帮助将参数dayfirst=True添加到

Maybe help add parameter dayfirst=True to to_datetime, if format of datetime is 30-01-2016:

dfx = df.ix[:,'a']
dfx = pd.to_datetime(dfx, dayfirst=True)

更通用的方法是将参数 format errors='coerce'一起使用,以将值替换为其他format:

More universal is use parameter format with errors='coerce' for replacing values with other format to NaN:

dfx = '30-01-2016'

dfx = pd.to_datetime(dfx, format='%d-%m-%Y', errors='coerce')
print (dfx)
2016-01-30 00:00:00

示例:

dfx = pd.Series(['30-01-2016', '15-09-2015', '40-09-2016'])
print (dfx)
0    30-01-2016
1    15-09-2015
2    40-09-2016
dtype: object

dfx = pd.to_datetime(dfx, format='%d-%m-%Y', errors='coerce')
print (dfx)
0   2016-01-30
1   2015-09-15
2          NaT
dtype: datetime64[ns]

如果格式是标准格式(例如01-30-201601-30-2016),则仅添加errors='coerce':

If format is standard (e.g. 01-30-2016 or 01-30-2016), add only errors='coerce':

dfx = pd.Series(['01-30-2016', '09-15-2015', '09-40-2016'])
print (dfx)
0    01-30-2016
1    09-15-2015
2    09-40-2016
dtype: object

dfx = pd.to_datetime(dfx, errors='coerce')
print (dfx)
0   2016-01-30
1   2015-09-15
2          NaT
dtype: datetime64[ns]

这篇关于ValueError:日期超出月份范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆