Pandas DateTime for Month

Tags: , ,



I have month column with values formatted as: 2019M01 To find the seasonality I need this formatted into Pandas DateTime format. How to format 2019M01 into datetime so that I can use it for my seasonality plotting? Thanks.

Answer

Use to_datetime with format parameter:

print (df)
      date
0  2019M01
1  2019M03
2  2019M04

df['date'] = pd.to_datetime(df['date'], format='%YM%m')
print (df)
        date
0 2019-01-01
1 2019-03-01
2 2019-04-01


Source: stackoverflow