简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM