Exploring Datetime Components in Python
Datetime components (year, month, day, hour, weekday, etc.) are essential for feature engineering, time-based analysis, and building robust data pipelines. In 2026, Python’s datetime module combined with pandas .dt accessor gives you clean, vectorized, and timezone-aware ways to extract and explore every part of a timestamp.
TL;DR — Most Useful Datetime Components
.year,.month,.day.hour,.minute,.second.weekday(),.day_name(),.isocalendar().date(),.time()for splitting
1. Basic Datetime Component Extraction
from datetime import datetime
from zoneinfo import ZoneInfo
now = datetime.now(ZoneInfo("UTC"))
print(f"Year: {now.year}")
print(f"Month: {now.month}, Day: {now.day}")
print(f"Hour: {now.hour}, Minute: {now.minute}")
print(f"Weekday: {now.weekday()} (0=Monday)")
print(f"Day name: {now.strftime('%A')}")
2. pandas .dt Accessor – Vectorized Power
import pandas as pd
# Small inline sample so this example runs as-is.
# In a real project you would load it with pd.read_csv("sales_data.csv")
df = pd.DataFrame({
"customer_id": [101, 102, 103, 104, 105, 106],
"customer_name": ["Ana", "Ben", "Chen", "Dana", "Eli", "Fay"],
"order_date": ["2026-01-05", "2026-01-12", "2026-02-03",
"2026-02-18", "2026-03-01", "2026-03-09"],
"amount": [1250.75, 890.50, 2340.00, 1780.25, 2615.40, 450.00],
"quantity": [3, 2, 5, 4, 6, 1],
"profit": [312.69, 222.63, 585.00, 445.06, 653.85, 112.50],
"region": ["North", "South", "East", "North", "West", "South"],
"category": ["Electronics", "Books", "Electronics", "Home", "Home", "Books"],
"rating": [5, 4, None, 3, 5, 4],
"year": [2025, 2025, 2026, 2026, 2026, 2026],
"description": ["fast laptop", "python book", "noise cancelling headphones",
"desk lamp", "standing desk", "data science book"],
})
df["order_date"] = pd.to_datetime(df["order_date"])
# Extract components in one line
df["year"] = df["order_date"].dt.year
df["month"] = df["order_date"].dt.month
df["day_of_week"] = df["order_date"].dt.day_name()
df["is_weekend"] = df["order_date"].dt.day_of_week.isin([5, 6])
df["quarter"] = df["order_date"].dt.quarter
print(df[["order_date", "year", "month", "day_of_week"]].head())
3. Real-World Data Science Exploration Examples
# Hourly sales pattern
hourly_pattern = df.groupby(df["order_date"].dt.hour)["amount"].mean()
# Monthly seasonality
monthly_sales = df.groupby(df["order_date"].dt.to_period("M"))["amount"].sum()
# Day-of-week analysis
dow_analysis = df.groupby(df["order_date"].dt.day_name())["amount"].agg(["mean", "count"])
print(monthly_sales)
print(dow_analysis)
4. Best Practices in 2026
- Always use timezone-aware datetimes with
zoneinfo - Parse dates early with
parse_datesorpd.to_datetime() - Use pandas
.dtaccessor for vectorized component extraction - Extract components only when needed for modeling or reporting
- Store original datetime column and derived features separately
Component Reference
Most components are plain attributes: year, month, day, hour, minute, second and microsecond. A few are methods: weekday() returns 0 for Monday through 6 for Sunday, isoweekday() returns 1 to 7, and isocalendar() returns the ISO year, week number and weekday. For names, use strftime("%A") or strftime("%B"), which follow the current locale. In pandas the same information is under the .dt accessor, for example .dt.dayofweek, .dt.isocalendar().week and .dt.quarter.
Extracted components are most useful as features: models rarely learn much from a raw timestamp, but they can learn that weekends, month ends or certain hours behave differently. Keep the original datetime column too, so you can always recompute features after fixing a time zone or adding a new one.
Worked Example: Calendar Features for a Model
from datetime import date, timedelta
d = date(2026, 12, 31)
iso = d.isocalendar()
print(d.weekday(), d.isoweekday()) # 3 4 (Thursday)
print(iso.year, iso.week, iso.weekday) # 2026 53 4
print(d.strftime("%A %d %B")) # Thursday 31 December
def calendar_features(day: date) -> dict:
return {
"month": day.month,
"quarter": (day.month - 1) // 3 + 1,
"iso_week": day.isocalendar().week,
"is_weekend": day.weekday() >= 5,
"is_month_end": (day + timedelta(days=1)).month != day.month,
}
print(calendar_features(date(2026, 2, 28)))
print(calendar_features(date(2026, 3, 14)))
Notice that 31 December 2026 falls in ISO week 53. ISO week numbers can belong to a neighbouring year, so always pair iso.week with iso.year rather than the calendar year.
Common Mistakes
- Confusing
weekday()andisoweekday(): Monday is 0 in one and 1 in the other - Combining an ISO week with the calendar year near New Year
- Extracting components before converting time zones: the hour depends on the zone
Quick Summary
- Attributes for numbers,
strftimefor names isocalendar()for week-based reporting- Use
.dtto extract components from a whole pandas column at once
Conclusion
Exploring datetime components is a fundamental skill that unlocks powerful time-based insights in data science. In 2026, the combination of Python’s datetime and pandas .dt gives you clean, efficient, and timezone-safe tools to extract year, month, weekday, hour, and many other components for feature engineering, seasonality analysis, and reporting.
Next steps:
- Open one of your datasets containing datetime columns and explore its components using
.dtaccessor