Home > front end >  Python: Formatting columns with mixed string and date values
Python: Formatting columns with mixed string and date values

Time:10-05

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'))

CodePudding user response:

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           -           -
  • Related