Siddharth
Siddharth

Reputation: 192

How to convert a date column of object datatype to datetime in pandas without changing the format

I am trying to convert a Date column of object datatype into datetime format but it is changing my format. My dataframe consists of all dates in May 2022 and my date column looks like this, which is of object datatype -

Date
04/05/2022
03/05/2022
01/05/2022
26/05/2022
10/05/2022

This is what my Date column looks like after running a pd.to_datetime() function -

Converted_Date
2022-05-04
2022-03-05
2022-01-05
2022-05-26
2022-10-05

I want the date format to be "yyyy-mm-dd" but after converting the datatype, some of my dates are in the format "yyyy-mm-dd" and others are in the format "yyyy-dd-mm". How can I make sure its consistent? Any help would be appreciated.

Upvotes: 0

Views: 156

Answers (1)

Ynjxsjmh
Ynjxsjmh

Reputation: 29982

You can use dayfirst argument of pd.to_datetime

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

Upvotes: 1

Related Questions