20

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

Can anyone help?

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Niladri Gomes
  • 213
  • 1
  • 2
  • 4
  • 2
    What's the value of `dfx`? – Barmar May 17 '16 at 20:22
  • 1
    possible duplicate of http://stackoverflow.com/questions/17690738/in-pandas-how-do-i-convert-a-string-of-date-strings-to-datetime-objects-and-put – badgley May 18 '16 at 03:00
  • Does this answer your question? [In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame?](https://stackoverflow.com/questions/17690738/in-pandas-how-do-i-convert-a-string-of-date-strings-to-datetime-objects-and-put) – gsamaras May 27 '23 at 15:17

2 Answers2

27

Maybe help add parameter dayfirst=True to to_datetime, if format of datetime is 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:

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':

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]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
-1

Well in my case

year = 2023
month = 2
date = datetime.date(year, month, 30)

got me this error because February month has 29 or 28 days in it. Maybe that point helps someone

Hasnain Sikander
  • 341
  • 3
  • 13