Home > Back-end >  How to convert dates of a column from one format to another using pandas in python?
How to convert dates of a column from one format to another using pandas in python?

Time:02-10

I am trying to convert date from "16-Dec-21" format to "2021-12-01" format using Pandas in Python in a CSV file. Here's the table:

Date ID
16-Dec-21 5665
11-Jan-22 5613
04-Feb-22 5680

Here's my code:

ds_com['Date'] = pd.to_datetime(ds_com['Date']).dt.strftime('%Y-%m-%d')

I've also tried

ds_com['Date'] = ds_com['Date'].dt.strftime('%Y-%m-%d')

But it also didn't work.

The new table should look like this:

Date ID
2021-12-16 5665
2022-01-11 5613
2022-02-04 5680

The table has hundreds of rows.

The current output shows as this when I open the ds_com.csv file in Excel:

Date ID
12/16/21 5665
1/11/22 5613
2/4/22 5680

The output shows correctly for

print(ds_com['Date'][1])

Thank you.

CodePudding user response:

You could try this. It would cause excel to not auto format

ds_com['Date'] = pd.to_datetime(ds_com['Date']).dt.strftime('="%Y-%m-%d"')
  • Related