Math with Dates in Python – Complete Guide for Data Science 2026
Performing math with dates — adding days, subtracting weeks, calculating differences, or projecting future dates — is one of the most essential skills in data science. Whether you’re building rolling windows, calculating customer lifetime, measuring freshness, or creating time-based features, Python’s timedelta and relativedelta make date arithmetic clean, accurate, and powerful.
TL;DR — Key Tools for Date Math
timedelta→ days, hours, minutes, secondsdateutil.relativedelta→ months, years, weeks- pandas
.dtaccessor for vectorized operations - Always work with timezone-aware datetimes
1. Basic Date Arithmetic with timedelta
from datetime import date, timedelta
from zoneinfo import ZoneInfo
today = date.today()
# Add time
tomorrow = today + timedelta(days=1)
next_week = today + timedelta(weeks=1)
future = today + timedelta(days=30, hours=6)
# Subtract time
last_week = today - timedelta(weeks=1)
print(f"Last week: {last_week}")
2. Advanced Math with relativedelta
from dateutil.relativedelta import relativedelta
# Add months or years (timedelta cannot do this accurately)
next_month = date.today() + relativedelta(months=1)
next_year = date.today() + relativedelta(years=1)
# End of month handling
end_of_month = date(2026, 3, 31) + relativedelta(months=1) # correctly becomes April 30
3. Real-World Data Science Examples
import pandas as pd
df = pd.read_csv("sales_data.csv", parse_dates=["order_date"])
# Current time
now = pd.Timestamp.now(tz="UTC")
# Math with dates in pandas
df["days_since_order"] = (now - df["order_date"]).dt.days
df["projected_delivery"] = df["order_date"] + pd.Timedelta(days=14)
df["one_month_ago"] = df["order_date"] - pd.Timedelta(days=30)
# Rolling window example
df["sales_7_days_ago"] = df["amount"].shift(7)
4. Best Practices in 2026
- Use
timedeltafor day/hour/minute arithmetic - Use
relativedeltafor month/year calculations - Prefer pandas
Timedeltaand.dtfor large DataFrames - Always perform calculations on timezone-aware datetimes
- Store original dates and derived math columns separately
Conclusion
Math with dates is a core skill for any data scientist. In 2026, the combination of timedelta, relativedelta, and pandas vectorized operations lets you perform accurate time-based feature engineering, projections, and freshness analysis with clean, readable code.
Next steps:
- Add time-delta features (days since order, projected delivery, etc.) to one of your current datasets