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.day_of_week # 0 = Monday
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.day_of_year
# Boolean flags
df["is_weekend"] = df["timestamp"].dt.day_of_week >= 5
df["is_month_end"] = df["timestamp"].dt.is_month_end
print(df[["timestamp", "quarter", "week_of_year", "is_weekend"]])
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
Methods vs Attributes
On a datetime object, year, month, day, hour and minute are attributes, while weekday(), isoweekday() and isocalendar() are methods that need parentheses. weekday() counts Monday as 0; isoweekday() counts Monday as 1. In pandas the .dt accessor exposes the same ideas as vectorised properties, for example .dt.day_of_week and .dt.quarter, and as methods for names such as .dt.day_name().
Worked Example: Calendar Features for a Sales Table
import pandas as pd
orders = pd.DataFrame({
"ts": pd.to_datetime(["2026-03-27 09:15", "2026-03-28 18:40",
"2026-03-31 23:05", "2026-04-01 07:30"]),
"amount": [120, 75, 210, 60],
})
features = orders.assign(
date=orders["ts"].dt.date,
hour=orders["ts"].dt.hour,
day_name=orders["ts"].dt.day_name(),
iso_week=orders["ts"].dt.isocalendar().week,
is_weekend=orders["ts"].dt.day_of_week >= 5,
month_end=orders["ts"].dt.is_month_end,
)
print(features[["day_name", "hour", "iso_week", "is_weekend", "month_end"]])
# day_name hour iso_week is_weekend month_end
# 0 Friday 9 13 False False
# 1 Saturday 18 13 True False
# 2 Tuesday 23 14 False True
# 3 Wednesday 7 14 False False
print(features.groupby("is_weekend")["amount"].sum())
Where These Features Are Used
Calendar components are some of the most useful features in reporting and machine learning. Sales often depend on the day of the week, traffic on the hour, and budgets on the quarter or month end. Extracting them once into columns lets you group, pivot and plot without repeating date logic. Keep the original timestamp column too, so you can always rebuild features or slice by exact time ranges later.
When the data covers several countries, convert timestamps to each customer's local zone before extracting the hour or weekday. Otherwise a Monday-morning order in Karachi can appear as a Sunday-night order in UTC, and every weekday chart will be slightly wrong.
Remember that day_of_week starts at 0 for Monday, while many spreadsheets start counting at Sunday, so label the values before sharing a chart.
Use dt.day_name() for labels.
Common Mistakes
- Calling
dt.weekdayin a loop: use vectorised.dtproperties on the whole column - Confusing ISO weeks with calendar weeks: ISO week 1 is the week containing the first Thursday
- Extracting components from strings: convert with
pd.to_datetime()first - Ignoring timezones: the hour of a UTC timestamp may be a different day locally
Quick Summary
- Attributes for parts, methods for weekday and ISO calendar values
- Use
.dtin pandas and preferday_of_week/day_of_year - Create calendar features once, then group and filter on them
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