Dates in Python

Dates And Time Mar 19, 2026

Dates in Python

The date class from Python’s datetime module is the foundation for working with calendar dates in data science. Whether you need to extract the current date, create specific dates for feature engineering, compare dates, or perform date arithmetic, mastering date objects is essential for clean, reliable, and timezone-aware time-based analysis.

TL;DR — Core Date Operations

  • date.today() → current date
  • date(year, month, day) → create specific date
  • .year, .month, .day, .weekday() → extract components
  • timedelta for date arithmetic

1. Creating and Getting Dates

from datetime import date

# Current date
today = date.today()
print(today)

# Specific date
birthday = date(2026, 3, 19)
print(birthday)

# From string (common in data files)
from datetime import datetime
dt = datetime.strptime("2026-03-19", "%Y-%m-%d").date()
print(dt)

2. Extracting Date Components

d = date(2026, 3, 19)

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

3. Real-World Data Science Examples

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"])

# Convert to pure date (drop time component)
df["order_date_only"] = df["order_date"].dt.date

# Extract useful date features
df["order_year"] = df["order_date_only"].apply(lambda x: x.year)
df["order_month"] = df["order_date_only"].apply(lambda x: x.month)
df["order_day"] = df["order_date_only"].apply(lambda x: x.day)
df["is_weekend"] = df["order_date_only"].apply(lambda x: x.weekday() in (5, 6))

4. Date Arithmetic

from datetime import timedelta

today = date.today()

# Add/subtract days
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)

# Days between two dates
delta = birthday - today
print(f"Days until birthday: {delta.days}")

5. Best Practices in 2026

  • Use date when you only need the date part (no time)
  • Always combine with datetime and zoneinfo for full timestamp needs
  • Use pandas .dt.date for vectorized conversion on DataFrames
  • Store dates in UTC where possible and convert for display
  • Use date objects in sets or as dict keys (they are hashable)

date Objects in Brief

A datetime.date stores a calendar date only: year, month and day, with no time and no time zone. It is the right type for birthdays, due dates and daily reports, where a time of day would add confusion.

Dates can be compared, sorted and subtracted. Subtracting two dates returns a timedelta whose days attribute gives the gap in days, and date.fromisoformat parses strings such as "2026-03-19".

In pandas, a datetime column normalised to midnight plays the same role, and .dt.date returns plain date objects when needed.

Worked Example: Due Dates and Gaps

We parse dates, sort them and measure gaps.

from datetime import date

invoices = ["2026-03-19", "2026-01-05", "2026-02-28"]
dates = sorted(date.fromisoformat(s) for s in invoices)
print(dates)

gaps = [(b - a).days for a, b in zip(dates, dates[1:])]
print(gaps)

due = date(2026, 4, 1)
print([(due - d).days for d in dates])

Sorting puts the invoices in date order. The gaps between them are 54 and 19 days, and the days remaining until 1 April 2026 are 86, 32 and 13.

Common Mistakes

  • Using datetime when only a date is needed.
  • Comparing date strings instead of date objects.
  • Forgetting that subtraction returns a timedelta.
  • Parsing ISO strings by hand.

Quick Summary

  • date holds year, month and day.
  • Dates compare, sort and subtract.
  • fromisoformat parses ISO strings.
  • Use .dt.date for pandas columns.

Conclusion

The date class in Python is simple yet powerful for all calendar-date operations in data science. In 2026, use it for clean feature engineering, date comparisons, and any situation where you only need the date part without time. Combine it with timedelta for easy date arithmetic and pandas for large-scale processing.

Next steps:

  • Explore one of your datasets containing datetime columns and extract pure date components for new 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