Time Travel in Python: Adding and Subtracting Time with timedelta – Data Science 2026
Adding and subtracting time is one of the most common operations in data science — calculating days since last purchase, projecting future dates, creating rolling windows, or measuring freshness of data. Python’s timedelta class from the datetime module makes “time travel” simple, precise, and readable.
TL;DR — Core timedelta Usage
timedelta(days=..., hours=..., minutes=...)- Use
+and-withdatetimeobjects - Works seamlessly with pandas
.dtaccessor - Always work with timezone-aware datetimes in 2026
1. Basic Time Travel Operations
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
now_utc = datetime.now(ZoneInfo("UTC"))
# Add time
future = now_utc + timedelta(days=30, hours=6, minutes=45)
print("30 days and 6h45m from now:", future)
# Subtract time
past = now_utc - timedelta(weeks=2, days=3)
print("2 weeks and 3 days ago:", past)
2. Real-World Data Science Examples
import pandas as pd
df = pd.read_csv("sales_data.csv", parse_dates=["order_date"])
# Current time for freshness analysis
current_utc = datetime.now(ZoneInfo("UTC"))
# Calculate time differences
df["hours_since_order"] = (current_utc - df["order_date"]).dt.total_seconds() / 3600
df["days_since_order"] = (current_utc - df["order_date"]).dt.days
# Future projection
df["projected_delivery"] = df["order_date"] + timedelta(days=14)
# Rolling window example
df["sales_7_days_ago"] = df["amount"] - (df["amount"].shift(7) if "amount" in df else 0)
3. Advanced timedelta Techniques
# Relative time calculations
one_month_ago = now_utc - timedelta(days=30) # approximate
exact_one_month_ago = now_utc.replace(month=now_utc.month-1) if now_utc.month > 1 else ...
# Business day calculations (simple example)
business_days = timedelta(days=5) # 5 business days forward
4. Best Practices in 2026
- Always use timezone-aware datetimes with
ZoneInfo - Prefer
timedeltaover manual arithmetic for clarity and accuracy - Use pandas
.dtaccessor for vectorized time calculations on DataFrames - Store original timestamps and derived time features separately
- Consider
dateutil.relativedeltafor complex calendar arithmetic (months/years)
Conclusion
Time travel in Python with timedelta is simple yet incredibly powerful for data science. In 2026, combining timedelta with timezone-aware datetime objects and pandas .dt accessor lets you perform freshness checks, rolling calculations, projections, and feature engineering with clean, readable, and accurate code.
Next steps:
- Open one of your datasets with datetime columns and add useful time-delta features using the patterns above