Exploring Datetime Components in Python

Datatypes Mar 19, 2026

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_dates or pd.to_datetime()
  • Use pandas .dt accessor 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() and isoweekday(): 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, strftime for names
  • isocalendar() for week-based reporting
  • Use .dt to 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 .dt accessor

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices