Reputation: 5
I want to convert a pandas column with year and month to monthend by using below statement
df['Month'] = df['Month'] + MonthEnd(1)
Month
202108
202107
202106
My ideal output is
Month
2021-08-31
2021-07-31
2021-06-30
But the output becomes
Month
1970-01-31 00:00:000202108
1970-01-31 00:00:000202107
1970-01-31 00:00:000202106
How can I convert the column back to the previous format? Or how can I get the monthend correctly?
Upvotes: 0
Views: 42
Reputation: 195418
Convert the "Month" column to datetime and then add MonthEnd(1)
:
from pandas.tseries.offsets import MonthEnd
df["Month"] = pd.to_datetime(df["Month"], format="%Y%m") + MonthEnd(0)
print(df)
Prints:
Month
0 2021-08-31
1 2021-07-31
2 2021-06-30
EDIT: Changed to + MonthEnd(0)
Upvotes: 1