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
365 views
in Technique[技术] by (71.8m points)

python - pd.to_datetime is getting half my dates with flipped day / months

My dataset has dates in the European format, and I'm struggling to convert it into the correct format before I pass it through a pd.to_datetime, so for all day < 12, my month and day switch. Is there an easy solution to this?

import pandas as pd
import datetime as dt
df = pd.read_csv(loc,dayfirst=True)
df['Date']=pd.to_datetime(df['Date'])

Is there a way to force datetime to acknowledge that the input is formatted at dd/mm/yy?

Thanks for the help!

Edit, a sample from my dates:

renewal["Date"].head()
Out[235]: 
0    31/03/2018
2    30/04/2018
3    28/02/2018
4    30/04/2018
5    31/03/2018
Name: Earliest renewal date, dtype: object

After running the following:

renewal['Date']=pd.to_datetime(renewal['Date'],dayfirst=True)

I get:

Out[241]: 
0    2018-03-31  #Correct
2    2018-04-01   #<-- this number is wrong and should be 01-04 instad
3    2018-02-28   #Correct
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Add format.

df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y') 

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

...