Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

python - ValueError: day is out of range for month

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...