2
我想將字符串從數據框轉換爲日期時間。ValueError:日期超出月份範圍
dfx = df.ix[:,'a']
dfx = pd.to_datetime(dfx)
但它提供了以下錯誤:
ValueError: day is out of range for month
誰能幫助?
我想將字符串從數據框轉換爲日期時間。ValueError:日期超出月份範圍
dfx = df.ix[:,'a']
dfx = pd.to_datetime(dfx)
但它提供了以下錯誤:
ValueError: day is out of range for month
誰能幫助?
也許有助於增加參數dayfirst=True
到to_datetime
,如果日期時間的格式爲30-01-2016
:
dfx = df.ix[:,'a']
dfx = pd.to_datetime(dfx, dayfirst=True)
更普遍的是使用參數format
與errors='coerce'
與其他format
到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-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]
什麼價值'dfx'? – Barmar
http://stackoverflow.com/questions/17690738/in-pandas-how-do-i-convert-a-string-of-date-strings-to-datetime-objects-and-put的可能重複 – badgley