How to Use dt.year in pandas to Extract Year from Dates
Use
dt.year on a pandas Series with datetime values to extract the year as an integer. This works only if the Series is of datetime type, such as datetime64[ns].Syntax
The syntax to extract the year from a pandas datetime Series is:
series.dt.yearHere, series is a pandas Series with datetime values. The dt accessor allows datetime properties to be accessed, and year returns the year part as an integer.
python
series.dt.year
Example
This example shows how to create a pandas DataFrame with a datetime column and extract the year using dt.year.
python
import pandas as pd data = {'date': ['2023-01-15', '2022-07-30', '2021-12-05']} df = pd.DataFrame(data) df['date'] = pd.to_datetime(df['date']) df['year'] = df['date'].dt.year print(df)
Output
date year
0 2023-01-15 2023
1 2022-07-30 2022
2 2021-12-05 2021
Common Pitfalls
Common mistakes when using dt.year include:
- Trying to use
dt.yearon a column that is not datetime type, which causes an error. - Forgetting to convert strings to datetime using
pd.to_datetime().
Example of wrong and right usage:
python
import pandas as pd data = {'date': ['2023-01-15', '2022-07-30']} df = pd.DataFrame(data) # Wrong: 'date' is string, dt.year will raise error try: df['year'] = df['date'].dt.year except AttributeError as e: print(f'Error: {e}') # Right: convert to datetime first df['date'] = pd.to_datetime(df['date']) df['year'] = df['date'].dt.year print(df)
Output
Error: Can only use .dt accessor with datetimelike values
date year
0 2023-01-15 2023
1 2022-07-30 2022
Quick Reference
| Operation | Description | Example |
|---|---|---|
| Extract year | Get year from datetime Series | series.dt.year |
| Convert to datetime | Convert string to datetime | pd.to_datetime(series) |
| Error if not datetime | dt.year fails if Series not datetime | Use pd.to_datetime() first |
Key Takeaways
Use dt.year on a pandas datetime Series to get the year as an integer.
Always convert string dates to datetime with pd.to_datetime() before using dt.year.
dt.year raises an error if used on non-datetime Series.
The dt accessor provides many datetime properties like year, month, day.
Extracting year helps in time-based analysis and grouping.