Python: Formatting columns with mixed string and date values

Question:

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?

*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'))
Asked By: Bloom

||

Answers:

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           -           -
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.