How to Use dt.month in pandas to Extract Month from Dates
In pandas, you can use
dt.month to extract the month as an integer from a datetime column in a DataFrame or Series. This attribute returns values from 1 (January) to 12 (December) for each date entry.Syntax
The dt.month attribute is used on a pandas Series or DataFrame column that contains datetime values. It extracts the month part as an integer (1 to 12) from each datetime entry.
Syntax pattern:
your_datetime_series.dt.month
Here, your_datetime_series must be of datetime type (e.g., datetime64[ns]).
python
your_datetime_series.dt.month
Example
This example shows how to create a pandas DataFrame with a datetime column and extract the month from it using dt.month.
python
import pandas as pd data = {'date': ['2023-01-15', '2023-05-20', '2023-12-31']} df = pd.DataFrame(data) df['date'] = pd.to_datetime(df['date']) # Convert to datetime df['month'] = df['date'].dt.month print(df)
Output
date month
0 2023-01-15 1
1 2023-05-20 5
2 2023-12-31 12
Common Pitfalls
Common mistakes when using dt.month include:
- Trying to use
dt.monthon columns that are not datetime type, which causes an error. - Forgetting to convert strings to datetime before using
dt.month.
Always ensure your column is converted using pd.to_datetime() before extracting the month.
python
import pandas as pd data = {'date': ['2023-01-15', '2023-05-20', '2023-12-31']} df = pd.DataFrame(data) # Wrong: This will raise an error because 'date' is string type # df['month'] = df['date'].dt.month # Right: Convert to datetime first df['date'] = pd.to_datetime(df['date']) df['month'] = df['date'].dt.month print(df)
Output
date month
0 2023-01-15 1
1 2023-05-20 5
2 2023-12-31 12
Quick Reference
Summary tips for using dt.month:
- Use only on datetime columns or Series.
- Returns integer month values from 1 to 12.
- Convert strings to datetime with
pd.to_datetime()first. - Works well for filtering or grouping data by month.
Key Takeaways
Use
dt.month on datetime columns to get month numbers from 1 to 12.Always convert string dates to datetime type with
pd.to_datetime() before using dt.month.Applying
dt.month on non-datetime columns causes errors.Extracted month values help in filtering and grouping data by month.
The
dt accessor provides many other datetime parts like day, year, and weekday.