2016-05-17 198 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] 
相關問題