To extract the month from a datetime column in pandas, you can access the “month” property. The “month” property returns a 64-bit integer.
import pandas as pd
df = pd.DataFrame({
"date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"],
"sales": [100,30,50,60,10,80]
})
df["date"] = pd.to_datetime(df["date"])
df["month"] = df["date"].dt.month
print(df)
#Output:
date sales month
0 2021-09-30 100 9
1 2021-12-31 30 12
2 2022-03-31 50 3
3 2022-06-30 60 6
4 2022-09-30 10 9
5 2022-12-31 80 12
When working with data which contains information over time, the ability to extract certain pieces of information from our data easily is valuable.
One such piece of information is getting the month from a date when using pandas in Python.
To get the month number from a datetime column in pandas, you can access the pandas datetime “month” property. The “month” property returns a 64-bit integer.
Below is a simple example which shows you how to get the month, as a number, from a date column in a pandas DataFrame.
import pandas as pd
df = pd.DataFrame({
"date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"],
"sales": [100,30,50,60,10,80]
})
df["date"] = pd.to_datetime(df["date"])
df["month"] = df["date"].dt.month
print(df)
#Output:
date sales month
0 2021-09-30 100 9
1 2021-12-31 30 12
2 2022-03-31 50 3
3 2022-06-30 60 6
4 2022-09-30 10 9
5 2022-12-31 80 12
Get Month Name from Datetime in pandas
If you want to get the name of the month from a datetime, instead of just the month number, then you can use pandas datetime month_name() function.
The month_name() function returns the name of the month.
Below is the same DataFrame as above but now we will get the month names for each datetime in the date column.
import pandas as pd
df = pd.DataFrame({
"date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"],
"sales": [100,30,50,60,10,80]
})
df["date"] = pd.to_datetime(df["date"])
df["month_name"] = df["date"].dt.month_name()
print(df)
#Output:
date sales month_name
0 2021-09-30 100 September
1 2021-12-31 30 December
2 2022-03-31 50 March
3 2022-06-30 60 June
4 2022-09-30 10 September
5 2022-12-31 80 December
Hopefully this article has been useful for you to learn how to extract the month from a date variable in a pandas DataFrame in Python.