Extracting Temporal Features
Use the .dt accessor to pull year, month, day, day_of_week, and hour out of a datetime column for feature engineering.
Why Extract Temporal Features?
A raw datetime64 column is opaque to most machine learning algorithms — they cannot understand that 2024-12-25 is a holiday or that Friday drives higher retail sales. Temporal feature engineering extracts meaningful components from datetime columns — year, month, day, weekday, hour — as separate numeric or categorical columns that models and analysis functions can act on directly.
The .dt Accessor
When a DataFrame column has datetime64 dtype, the .dt accessor exposes all datetime properties and methods vectorially. Instead of applying a Python function row by row, you write df['date'].dt.year and Pandas computes the year for every row in a single fast operation. The same accessor works on timedelta64 columns with different properties.
import pandas as pd
df = pd.DataFrame({
'event_date': pd.date_range('2024-01-01', periods=8, freq='D'),
'revenue': [200, 350, 280, 310, 420, 380, 190, 260]
})
# Access datetime properties with .dt
print(df['event_date'].dt.year) # 2024 for all
print(df['event_date'].dt.month) # 1 for all
print(df['event_date'].dt.day[:5]) # 1, 2, 3, 4, 5All lessons in this course
- DatetimeIndex and Period Ranges
- Resampling Time Series
- Shifting and Lag Features
- Extracting Temporal Features