'Why is my function parameter for Pandas to_datetime() being ignored?

I have a Pandas data frame with a column containing months and years. Unfortunately, the values are currently string objects not datetime objects; This means that if sorting by this column, the sort goes in numerical rather than chronological order. For example, 01 2020, 01 2021, 01 2022, 02 2020... etc. I am attempting to convert the column to datetime objects using the pandas.to_datetime() function as documented here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html This works just fine, but unfortunately changes my format to yyyy-mm-dd (making up the day value since there isn't one, and arbitrarily setting it to 01).

I've used the format="" parameter, but it doesn't seem to change anything. temp_df['Month'] = pd.to_datetime(temp_df['Month'], format="%m %Y") still results in the same date format, as if my format parameter had been %Y-%m-%d. I've googled this a bunch and come across a number of articles and previous stack overflow posts that tell me how to solve this problem - but their solution is what I'm doing, using to_datetime(df, format). Oh, and this is in a Jupyter notebook if that matters. Appreciate the help in advance!~



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source