ValueError: the day is out of range for the month

I want to convert a string from dataframe to datetime.

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

But this leads to the following error:

ValueError: day out of range for a month

Can anyone help?

+4
source share
1 answer

Perhaps add the parameter dayfirst=Trueto to_datetimeif the date and time format is 30-01-2016:

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

More universal is the use parameter formatwith errors='coerce'to replace the values ​​with others formatby NaN:

dfx = '30-01-2016'

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

Example:

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 the format is standard (e.g., 01-30-2016or 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]
+5

All Articles