Python ValueError:日期超出月份的范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37285365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ValueError: day is out of range for month
提问by Niladri Gomes
I want to convert a string from a dataframe to datetime.
我想将字符串从数据帧转换为日期时间。
dfx = df.ix[:,'a']
dfx = pd.to_datetime(dfx)
But it gives the following error:
但它给出了以下错误:
ValueError: day is out of range for month
ValueError:日期超出月份的范围
Can anyone help?
任何人都可以帮忙吗?
回答by jezrael
Maybe help add parameter dayfirst=True
to to_datetime
, if format of datetime is 30-01-2016
:
也许帮助添加参数dayfirst=True
到to_datetime
,如果日期时间格式为30-01-2016
:
dfx = df.ix[:,'a']
dfx = pd.to_datetime(dfx, dayfirst=True)
More universal is use parameter format
with errors='coerce'
for replacing values with other format
to NaN
:
更通用的是使用参数format
witherrors='coerce'
用其他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
Sample:
样本:
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]
If format is standard (e.g. 01-30-2016
or 01-30-2016
), add only errors='coerce'
:
如果格式是标准的(例如01-30-2016
或01-30-2016
),只添加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]