Attributes of a Date in Python

Dates And Time Mar 19, 2026

Attributes of a Date in Python

Understanding the attributes of Python’s date object is fundamental for effective date-based feature engineering, reporting, and time-series analysis. The date class provides direct, efficient access to year, month, day, weekday, and other calendar properties without the complexity of full datetime objects.

TL;DR — Key Attributes & Methods

  • .year, .month, .day → core calendar components
  • .weekday() and .isoweekday() → weekday information
  • .strftime() → flexible string formatting
  • .isoformat() → standard ISO string representation

1. Basic Date Attributes

from datetime import date

d = date(2026, 3, 19)

print(f"Year: {d.year}")
print(f"Month: {d.month} ({d.strftime('%B')})")
print(f"Day: {d.day}")
print(f"Weekday number (0=Monday): {d.weekday()}")
print(f"ISO Weekday (1=Monday): {d.isoweekday()}")
print(f"Day name: {d.strftime('%A')}")

2. Real-World Data Science Usage with pandas

import pandas as pd

# Create a small demo file so this example runs as-is
# (in your project, sales_data.csv is your real export)
import numpy as np
rng = np.random.default_rng(42)
n = 60
pd.DataFrame({
    "order_id": range(1001, 1001 + n),
    "order_date": pd.date_range("2026-01-01", periods=n, freq="3D"),
    "customer_id": rng.integers(101, 121, n),
    "customer_name": rng.choice([" ana", "ben ", "chen", "dana"], n),
    "product_id": rng.integers(1, 9, n),
    "region": rng.choice(["North", "South", "East", "West"], n),
    "category": rng.choice(["Electronics", "Computers", "Books", "Home"], n),
    "payment_method": rng.choice(["card", "cash", "wallet"], n),
    "segment": rng.choice(["consumer", "business"], n),
    "quantity": rng.integers(1, 6, n),
    "amount": rng.uniform(50, 2500, n).round(2),
    "discount": rng.choice([0.0, 0.05, 0.1, 0.2], n),
}).assign(
    price=lambda d: (d["amount"] / d["quantity"]).round(2),
    profit=lambda d: (d["amount"] * rng.uniform(0.05, 0.3, n)).round(2),
).assign(
    ship_date=lambda d: d["order_date"] + pd.Timedelta(days=2),
    status=lambda d: np.where(d["amount"] > 2000, "priority", "standard"),
).to_csv("sales_data.csv", index=False)

df = pd.read_csv("sales_data.csv", parse_dates=["order_date"])

# Extract date attributes efficiently
df["order_year"] = df["order_date"].dt.year
df["order_month"] = df["order_date"].dt.month
df["order_day"] = df["order_date"].dt.day
df["order_weekday"] = df["order_date"].dt.day_of_week
df["order_day_name"] = df["order_date"].dt.day_name()
df["order_quarter"] = df["order_date"].dt.quarter

print(df[["order_date", "order_year", "order_month", "order_day_name"]].head())

3. Formatting and String Conversion

d = date.today()

print(d.isoformat())                    # 2026-03-19
print(d.strftime("%Y-%m-%d"))           # 2026-03-19
print(d.strftime("%A, %B %d, %Y"))      # Thursday, March 19, 2026
print(d.strftime("%d/%m/%Y"))           # 19/03/2026

4. Best Practices in 2026

  • Use pandas .dt accessor for vectorized extraction on large DataFrames
  • Prefer date objects when you only need the date part (no time component)
  • Always work with timezone-aware datetime objects and convert to .date() when needed
  • Use strftime() for human-readable reports and logging
  • Store original datetime columns and derived date attributes separately for flexibility

Reading Date Attributes

A date exposes year, month and day as attributes, and methods such as weekday(), isoweekday() and isocalendar() give derived values. isocalendar returns the ISO year, week number and weekday, which is useful for weekly reports.

In pandas, the same values come from the .dt accessor on a datetime column: .dt.year, .dt.month, .dt.day_of_week, .dt.quarter and .dt.isocalendar(). These work on the whole column at once.

Derived attributes are common model features, for example month for seasonality or day of week for traffic patterns.

Worked Example: ISO Weeks and Quarters

We extract ISO week numbers and quarters from a few dates.

from datetime import date
import pandas as pd

d = date(2026, 3, 19)
iso = d.isocalendar()
print(iso.year, iso.week, iso.weekday)

s = pd.Series(pd.to_datetime(["2026-01-01", "2026-03-19", "2026-12-31"]))
print(s.dt.quarter.tolist())
print(s.dt.isocalendar()["week"].tolist())

19 March 2026 is in ISO week 12 and is the fourth ISO weekday (Thursday). The pandas column gives quarters 1, 1 and 4, and ISO weeks 1, 12 and 53, because 31 December 2026 belongs to week 53 of the ISO year.

Practical Tips

Store derived attributes only when you need them repeatedly; otherwise compute them on the fly with .dt to keep tables small and avoid stale columns.

Also confirm the column dtype is datetime64 before using .dt, because string columns raise an AttributeError.

Common Mistakes

  • Confusing weekday() (Monday 0) with isoweekday() (Monday 1).
  • Assuming week numbers restart exactly on 1 January.
  • Looping over rows instead of using .dt.
  • Using deprecated pandas aliases.

Quick Summary

  • Dates expose year, month and day.
  • isocalendar gives ISO week numbers.
  • Use .dt for pandas columns.
  • Attributes make good features.

Conclusion

The attributes of a date object in Python provide clean, direct access to all essential calendar information. In data science, these attributes are heavily used for feature engineering, seasonality analysis, reporting, and building time-based insights. Combine Python’s date class with pandas .dt accessor to process large datasets efficiently and create powerful date-derived features.

Next steps:

  • Open one of your datasets containing datetime columns and explore its date attributes to create new time-based features

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