You can use np.where in combination with pandas' to_datetime function to achieve this. Here's an example:
import pandas as pd
import numpy as np
# create a sample dataframe
df = pd.DataFrame({'date': ['31-12-21', '01-01-22', '02-01-22']})
# use np.where to check if the date format is %d-%m-%y, and if so, convert it to %y-%m-%d
df['date'] = np.where(df['date'].str.match('\d{2}-\d{2}-\d{2}'),
pd.to_datetime(df['date'], format='%d-%m-%y').dt.strftime('%y-%m-%d'),
df['date'])
print(df)
Output:
date
0 21-12-31
1 22-01-01
2 22-01-02
In the above code, str.match
is used to check if the date format matches %d-%m-%y
. If it does, pd.to_datetime
is used to convert it to a datetime object and then dt.strftime
is used to convert it to the desired format %y-%m-%d
. If the date format does not match %d-%m-%y
, the original value is kept unchanged.
Asked: 2021-11-14 11:00:00 +0000
Seen: 7 times
Last updated: Mar 16 '22