Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 598
Anant Avatar asked Feb 19 '18 16:02

Anant


1 Answers

Add format.

df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y') 
like image 178
Martin Bobak Avatar answered Sep 19 '22 13:09

Martin Bobak