简体   繁体   中英

Converting a dataframe row with multiple date formats into a datetime

I have a dataframe that has two rows that need to be in datetime format so I can use them for calculations.

They are currently stored as strings in the formats dd/mm/yyyy mm/dd/yyyy mm/dd/yy

How can I convert them all into a singular format? I have tried using

dataframe['ADMISSION_DATE'] =pd.to_datetime(dataframe['ADMISSION_DATE'], format='%m%d%y').dt.strftime('%m/%d/%Y')

Rows that need to be changed

Assuming my assumption in the comment holds true, you can use this:

pd.to_datetime(df["ADMISSION_DATE"], format="%m/%d/%Y", errors="coerce"). \
    fillna(pd.to_datetime(df["ADMISSION_DATE"], format="%m/%d/%y", errors="coerce"))

You basically try to convert using the first format and whenever this fails, you try the second format.

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