Time Travel in Python: Adding and Subtracting Time is one of the most practical and frequently used features of the datetime module — enabling you to shift dates and times forward or backward with precision using timedelta. Whether calculating deadlines, aging records, scheduling events, analyzing time deltas between earthquakes, or simulating future/past states, Python makes time arithmetic clean, readable, and timezone-aware. In 2026, this remains foundational, enhanced by zoneinfo for modern timezone handling, Polars/Dask for fast columnar time shifts, pandas for familiar workflows, and Pydantic for validated time calculations. This guide covers timedelta creation, addition/subtraction, real-world patterns (earthquake age analysis, scheduling, time deltas), and modern best practices with type hints, performance, timezone awareness, and integration with Polars/pandas/Dask/zoneinfo.
Here’s a complete, practical guide to time travel in Python: timedelta basics, adding/subtracting intervals, custom durations, timezone considerations, real-world earthquake time calculations, and 2026 best practices with zoneinfo, Polars/pandas/Dask, type hints, and common pitfalls.
1. timedelta Basics — Building Time Intervals
from datetime import datetime, timedelta
# Basic intervals
one_day = timedelta(days=1)
three_hours = timedelta(hours=3)
thirty_minutes = timedelta(minutes=30)
custom = timedelta(days=2, hours=3, minutes=30, seconds=45, microseconds=123456)
print(custom) # 2 days, 3:30:45.000123
2. Adding & Subtracting Time — Simple Time Travel
now = datetime.now()
# Future
future = now + timedelta(days=7)
print(f"One week from now: {future}")
# Past
past = now - timedelta(weeks=1, hours=12)
print(f"One week and 12 hours ago: {past}")
# Custom travel
event = datetime(2025, 3, 1, 14, 0)
shifted = event + timedelta(days=2, hours=3, minutes=30)
print(f"Event shifted: {shifted}")
3. Real-world pattern: earthquake timestamp deltas & age analysis
import polars as pl
from datetime import datetime, timedelta, timezone
df = pl.read_csv('earthquakes.csv').with_columns(
pl.col('time').str.to_datetime().alias('dt')
)
# Time since each quake (from now, UTC)
now_utc = datetime.now(timezone.utc)
df = df.with_columns(
(now_utc - pl.col('dt')).alias('age')
)
# Age in days/hours
df = df.with_columns(
pl.col('age').dt.total_days().alias('days_old'),
(pl.col('age').dt.total_hours() % 24).alias('hours_old')
)
print(df.select('time', 'mag', 'days_old', 'hours_old').head(5))
# Filter quakes within last 24 hours
recent = df.filter(pl.col('age') <= timedelta(hours=24))
print(f"Quakes in last 24h: {recent.shape[0]}")
# Add/subtract fixed interval (e.g., forecast 7 days ahead)
df_forecast = df.with_columns(
(pl.col('dt') + timedelta(days=7)).alias('forecast_dt')
)
print(df_forecast.select('dt', 'forecast_dt').head())
Best practices for time travel in Python 2026
- Use timedelta — for all additions/subtractions: days, seconds, microseconds (no months/years — use
relativedeltafrom dateutil if needed). - Prefer timezone-aware datetimes —
datetime.now(timezone.utc)orZoneInfo— avoid naive arithmetic pitfalls. - Use Polars
dt.offset_by()— for fast columnar shifts:pl.col('dt').dt.offset_by('7d'). - Use pandas
Timedelta—df['dt'] + pd.Timedelta(days=7). - Use Dask
Timedelta— distributed time shifts. - Add type hints —
from datetime import datetime, timedelta; def shift_time(dt: datetime, delta: timedelta) -> datetime: .... - Use
replace()— for component-level changes (immutable):dt.replace(year=dt.year + 1). - Use
astimezone()— for timezone-safe arithmetic. - Handle DST/ambiguous times — use
zoneinfoorpytzlocalize/normalize. - Use
total_seconds()— for precise duration math. - Avoid naive + aware mixing — causes TypeError.
- Use Polars
str.to_datetime(time_zone="UTC")— for parsing with TZ. - Use pandas
to_datetime(utc=True)— similar. - Use
relativedeltafrom python-dateutil — for month/year additions (third-party). - Use
pendulum/arrow— for human-friendly time travel (third-party, optional).
Time travel in Python — adding/subtracting intervals with timedelta — is precise, readable, and timezone-aware. In 2026, prefer zoneinfo for TZ, Polars/pandas/Dask for columnar shifts, and type hints for safety. Master timedelta, and you’ll schedule, age, forecast, and analyze time-based data accurately in any workflow.
Next time you need to move forward or backward in time — reach for timedelta. It’s Python’s cleanest way to say: “Shift this datetime — by days, hours, minutes, or any custom interval — reliably and exactly.”