How to Extract Month from Datetime in pandas Easily
To extract the month from a datetime column in pandas, use the
.dt.month accessor on a datetime Series. This returns the month as an integer from 1 to 12 for each date.Syntax
Use the .dt.month attribute on a pandas Series that contains datetime values.
Series.dt.month: Extracts the month as an integer (1 to 12) from each datetime value.
python
df['date_column'].dt.monthExample
This example shows how to create a pandas DataFrame with a datetime column and extract the month from it.
python
import pandas as pd data = {'date_column': ['2023-01-15', '2023-05-20', '2023-12-31']} df = pd.DataFrame(data) df['date_column'] = pd.to_datetime(df['date_column']) df['month'] = df['date_column'].dt.month print(df)
Output
date_column month
0 2023-01-15 1
1 2023-05-20 5
2 2023-12-31 12
Common Pitfalls
One common mistake is trying to use .month directly on a pandas Series without the .dt accessor, which causes an error.
Wrong way:
df['date_column'].month # This raises an AttributeError
Right way:
df['date_column'].dt.month # Correct usage
python
import pandas as pd data = {'date_column': ['2023-01-15']} df = pd.DataFrame(data) df['date_column'] = pd.to_datetime(df['date_column']) # Wrong way (will raise error): # df['date_column'].month # Right way: month = df['date_column'].dt.month print(month)
Output
0 1
dtype: int64
Quick Reference
| Operation | Code Example | Description |
|---|---|---|
| Extract month | df['date_column'].dt.month | Gets month as integer (1-12) |
| Extract year | df['date_column'].dt.year | Gets year as integer |
| Extract day | df['date_column'].dt.day | Gets day of month as integer |
| Convert to datetime | pd.to_datetime(df['date_column']) | Converts string to datetime type |
Key Takeaways
Use the .dt accessor to work with datetime properties in pandas Series.
Extract the month with .dt.month to get integers from 1 to 12.
Always convert date strings to datetime type before extracting parts.
Avoid using .month directly on Series to prevent errors.