Convert string month year (where year is only a two digits) to datetime in pandas

Viewed 30

I have a data frame with a column month_year which is a string. Where the year is only a two digits. I would like to convert month_year column to a datetime column.

df:

month_year
Jan-98
Feb-98
Mar-99
Apr-99
May-99
Oct-00
Nov-00
Jun-01
Aug-03
Sep-08
Dec-21
Jul-22

Expected Output:

month_year
01-01-1998
01-02-1998
01-03-1999
01-04-1999
01-05-1999
01-10-2000
01-11-2000
01-06-2001
01-08-2003
01-09-2008
01-12-2021
01-07-2022

I have tried below code.

df['month_year'] = pd.to_datetime(df['month_year'])

and

df['month_year'] = pd.to_datetime(df['month_year']).dt.strftime('%m-%Y')

unfortunately both did not work.

1 Answers

You are close, need format with b for months first 3 letters and y for YY format of years:

df['month_year'] = pd.to_datetime(df['month_year'], format='%b-%y')
print (df)
   month_year
0  1998-01-01
1  1998-02-01
2  1999-03-01
3  1999-04-01
4  1999-05-01
5  2000-10-01
6  2000-11-01
7  2001-06-01
8  2003-08-01
9  2008-09-01
10 2021-12-01
11 2022-07-01
Related