Skip to content
Advertisement

How to convert two different date formats from a pandas dataframe column into same format?

I have two different date formats in a pandas column such as – DD-MM-YYYY and MM/DD/YYYY and I want to convert them into the same format.

I tried using the code –

JavaScript

but this converts the dates into DD/MM/YYYY and MM/DD/YYYY into the output – data[‘SALE DATE’]

enter image description here

I want a python solution to overcome this problem. Any leads will be very helpful.

Advertisement

Answer

The most intuitive solution is to write a custom conversion function, someting like:

JavaScript

and then pass it as a converter for the column in question:

JavaScript

I prepared a CSV file, which read with read_csv without any custom converter gave the original content and both columns of object type:

JavaScript

But reading the same file with the above converter gave:

JavaScript

with Date column of datetime64[ns] type and both dates from May, just as intended.

Or if you have this DataFrame from other source and you want to convert this column, run:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement