Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Formatting columns with mixed string and date values

My table:

ID Start Date End Date
01 2022-11-14 00:00:00 2023-05-11 00:00:00
02 2022-11-14 00:00:00 TBD
03 TBD TBD
04

The issue:

I would like to change the date format to '%d.%m.%Y' while keeping the string values.
Is there an efficient solution to this issue?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

*Dates are currently in '%Y-%m-%d %H:%M:%S' by default

My attempt for one column:

df['Start Date'] = df['Start Date'].apply(lambda x: pd.to_datetime(x, errors='ignore'))

>Solution :

You can apply to_datetime and dt.strftime on the date columns, then fillna with the original data and update the DataFrame:

df.update(
 df.filter(like='Date')
   .apply(lambda s: pd.to_datetime(s, errors='coerce').dt.strftime('%d.%m.%Y'))
   .fillna(df)
)

updated df:

   ID  Start Date    End Date
0   1  14.11.2022  11.05.2023
1   2  14.11.2022         TBD
2   3         TBD         TBD
3   4           -           -
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading