Home > Mobile >  Change Pandas date column format from "MMDDYYYY" to "YYYY-MM-DD"
Change Pandas date column format from "MMDDYYYY" to "YYYY-MM-DD"

Time:07-13

Example: 10011933 to 1933-10-01

Here's my data in a Pandas DataFrame:

date
10011933
04041961
07061931
10281988

My attempt to solve:

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

Error Message - I get the following error:

ValueError: unconverted data remains: 57

How would I correct to remove the error? Thanks.

CodePudding user response:

First parse the string column into a datetime

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

Then format the datetime into a string of your desired format

df['date_formatted'] = df['datetime'].dt.strftime('%Y%m%d')

Or you can do it all in one line if you desire

CodePudding user response:

Here is a working solution:

df['date_new'] = pd.to_datetime(df['date'],format='%m%d%Y').dt.strftime('%Y-%m-%d')

Where df['date_new'] gives the desired output

0    1933-10-01
1    1961-04-04
2    1931-07-06
3    1988-10-28
  • Related