'How to use to_date in panda for yyyy-mm-dd format to extract month name?

df["month"]=pd.to_datetime(df['date'],format="%y-%m-%d").dt.month_name() 
df.set_index('date', inplace=True)

I used this code to extract month name from the date series in my CSV file. All the dates had a format of yyyy-mm-dd. So i used %y-%m-%d to extract month name from the date. But I'm getting key error. Can u tell me where I made the mistake??

Errors: 0

1



Solution 1:[1]

Your format string is incorrect you need to use "%Y-%m-%d". %y is for two digit years, %Y is for four digit years.

you can read more here

Solution 2:[2]

You will need to use need the capital Y, not y

df["month"]=pd.to_datetime(df['date'],format="%Y-%m-%d").dt.month_name() 
df.set_index('date', inplace=True)

Output:

               new
month   
2022-02-01  February
2022-09-10  September

Solution 3:[3]

Alternatively, You can use lambda function applied on the date column of your dataframe by using the datetime library.

from datetime import datetime
df["month"] = df.date.apply(lambda x: datetime.strptime(x, "%Y-%m-%d").strftime('%B'))

More information about the formats could be found here. :)

https://docs.python.org/3/library/datetime.html

Output below:

enter image description here

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Patrick
Solution 2 Huy Hiep Nguyen
Solution 3 Siddhant Kaushal