Date column's format changing in pandas -python

Viewed 30

I have a dataframe df with Date column:

Date
--------
Wed 23 Dec
Sat 28 Nov
Thu 26 Nov
Sun 22 Nov
Tue 1 Dec
Wed 2 Dec

The Date column is object-type, I want to change the format using format="%m-%d-%Y" into yyyy-dd-mm

Expected output df:

Date
---------
2020-23-12
2020-28-11
2020-26-11
2020-22-11
2020-01-12
2020-02-12

Thanks in advance for the help!

1 Answers

Use to_datetime with format specified original data with added year, get column filled by datetimes:

df['Date'] = pd.to_datetime(df['Date']+'2020', format="%a %d %b%Y")
print (df)
        Date
0 2020-12-23
1 2020-11-28
2 2020-11-26
3 2020-11-22
4 2020-12-01
5 2020-12-02

If need custom format add Series.dt.strftime, but datetimes are lost, get strings:

df['Date'] = pd.to_datetime(df['Date']+'2020', format="%a %d %b%Y").dt.strftime("%Y-%d-%m")
print (df)
         Date
0  2020-23-12
1  2020-28-11
2  2020-26-11
3  2020-22-11
4  2020-01-12
5  2020-02-12
Related