DateTime Components – Extracting Year, Month, Day, Hour & More in Python 2026
Extracting specific components (year, month, day, hour, weekday, etc.) from datetime objects is a daily task in data manipulation. In 2026, Python provides clean and efficient ways to do this using the standard library and pandas.
TL;DR — Most Used Components
.year,.month,.day.hour,.minute,.second.weekday(),.isoweekday(),.strftime()- Pandas accessors:
.dt.year,.dt.month_name(), etc.
1. Using Standard datetime Module
from datetime import datetime
dt = datetime(2026, 3, 18, 14, 30, 45)
print("Year:", dt.year)
print("Month:", dt.month)
print("Day:", dt.day)
print("Hour:", dt.hour)
print("Minute:", dt.minute)
print("Weekday (0=Mon):", dt.weekday())
print("Weekday name:", dt.strftime("%A"))
print("Month name:", dt.strftime("%B"))
2. Pandas – Best for DataFrames
import pandas as pd
df = pd.DataFrame({
"timestamp": pd.date_range("2026-03-01", periods=5, freq="D")
})
df["year"] = df["timestamp"].dt.year
df["month"] = df["timestamp"].dt.month
df["day"] = df["timestamp"].dt.day
df["weekday"] = df["timestamp"].dt.weekday
df["month_name"] = df["timestamp"].dt.month_name()
df["day_name"] = df["timestamp"].dt.day_name()
print(df)
3. Advanced Component Extraction
# Quarter, week of year, day of year
df["quarter"] = df["timestamp"].dt.quarter
df["week_of_year"] = df["timestamp"].dt.isocalendar().week
df["day_of_year"] = df["timestamp"].dt.dayofyear
# Boolean flags
df["is_weekend"] = df["timestamp"].dt.weekday >= 5
df["is_month_end"] = df["timestamp"].dt.is_month_end
4. Best Practices in 2026
- Use
.dtaccessor in pandas for vectorized operations (much faster) - Prefer
strftime()only when you need formatted strings - Extract components early in your pipeline to avoid repeated parsing
- Use
zoneinfofor proper timezone handling when working with real-world timestamps
Conclusion
Mastering datetime component extraction is essential for any data manipulation workflow. In 2026, combine the standard datetime module for simple scripts with pandas .dt accessor for large datasets. Clean and early component extraction makes your analysis faster, more readable, and less error-prone.
Next steps:
- Review your current date-related code and replace manual string slicing with proper component access