2016-05-17 147 views
2

我想将字符串从数据框转换为日期时间。ValueError:日期超出月份范围

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

但它提供了以下错误:

ValueError: day is out of range for month

谁能帮助?

+1

什么价值'dfx'? – Barmar

+0

http://stackoverflow.com/questions/17690738/in-pandas-how-do-i-convert-a-string-of-date-strings-to-datetime-objects-and-put的可能重复 – badgley

回答

5

也许有助于增加参数dayfirst=Trueto_datetime,如果日期时间的格式为30-01-2016

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

更普遍的是使用参数formaterrors='coerce'与其他formatNaN替换值:

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'

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] 
相关问题