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 datedate(year, month, day)→ create specific date.year,.month,.day,.weekday()→ extract componentstimedeltafor 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
datewhen you only need the date part (no time) - Always combine with
datetimeandzoneinfofor full timestamp needs - Use pandas
.dt.datefor vectorized conversion on DataFrames - Store dates in UTC where possible and convert for display
- Use
dateobjects 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