DateTime Components – Extracting Year, Month, Day, Hour & More in Python 2026

Data Manipulation Mar 18, 2026

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 .dt accessor 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 zoneinfo for 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.weekday in a loop: use vectorised .dt properties 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 .dt in pandas and prefer day_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

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