How to Use dt Accessor in pandas for DateTime Operations
In pandas, the
dt accessor allows you to access datetime properties and methods on Series with datetime values. You can use it to extract parts like year, month, day, or perform datetime operations directly on the Series.Syntax
The dt accessor is used on a pandas Series containing datetime values. It provides access to datetime attributes and methods.
series.dt.attribute: Access a datetime attribute likeyear,month,day, etc.series.dt.method(): Call a datetime method likestrftime(),floor(),ceil(), etc.
python
series.dt.year
series.dt.month
series.dt.day
series.dt.strftime('%Y-%m-%d')Example
This example shows how to create a pandas Series with datetime values and use the dt accessor to extract the year, month, and day parts.
python
import pandas as pd # Create a Series with datetime values dates = pd.Series(pd.to_datetime(['2023-01-15', '2024-06-20', '2022-12-31'])) # Extract year, month, and day using dt accessor years = dates.dt.year months = dates.dt.month days = dates.dt.day print('Years:') print(years) print('\nMonths:') print(months) print('\nDays:') print(days)
Output
Years:
0 2023
1 2024
2 2022
dtype: int64
Months:
0 1
1 6
2 12
dtype: int64
Days:
0 15
1 20
2 31
dtype: int64
Common Pitfalls
Common mistakes when using the dt accessor include:
- Trying to use
dton a Series that is not datetime type, which causes an error. - Forgetting to convert strings to datetime using
pd.to_datetime()before usingdt. - Using unsupported attributes or methods that do not exist on the
dtaccessor.
Always ensure your Series is datetime type before using dt.
python
import pandas as pd # Wrong: Series with strings str_dates = pd.Series(['2023-01-15', '2024-06-20']) # This will raise an error try: print(str_dates.dt.year) except AttributeError as e: print(f'Error: {e}') # Right: Convert to datetime first dates = pd.to_datetime(str_dates) print(dates.dt.year)
Output
Error: Can only use .dt accessor with datetimelike values
0 2023
1 2024
dtype: int64
Quick Reference
| dt Accessor Attribute/Method | Description |
|---|---|
| year | Extracts the year from datetime |
| month | Extracts the month from datetime |
| day | Extracts the day from datetime |
| hour | Extracts the hour from datetime |
| minute | Extracts the minute from datetime |
| second | Extracts the second from datetime |
| weekday | Returns the day of the week (Monday=0) |
| strftime(format) | Formats datetime as string with given format |
| date | Returns the date part (without time) |
| time | Returns the time part (without date) |
Key Takeaways
Use the dt accessor on pandas Series with datetime type to access datetime parts easily.
Always convert string dates to datetime using pd.to_datetime() before using dt.
The dt accessor provides many useful attributes like year, month, day, and methods like strftime().
Using dt on non-datetime Series causes an AttributeError.
Refer to the quick reference table for common dt attributes and methods.