Creating timedeltas
The timedelta class from Python’s datetime module is the standard way to represent durations — the difference between two points in time. In data science, you create timedelta objects constantly for adding or subtracting time from dates, calculating session lengths, building rolling windows, projecting future events, and measuring time intervals.
TL;DR — How to Create a timedelta
timedelta(days=..., hours=..., minutes=..., seconds=...)- Supports
weeks,microseconds, and negative values - Use with
datetimeordatefor arithmetic - Pandas
Timedeltafor DataFrame operations
1. Basic timedelta Creation
from datetime import timedelta
# Common durations
one_day = timedelta(days=1)
one_week = timedelta(weeks=1)
three_hours = timedelta(hours=3)
two_hours_thirty_min = timedelta(hours=2, minutes=30)
# Negative duration (going backwards in time)
minus_five_days = timedelta(days=-5)
print(one_day)
print(two_hours_thirty_min)
2. Real-World Data Science Examples
import pandas as pd
from datetime import timedelta
from zoneinfo import ZoneInfo
df = pd.read_csv("sales_data.csv", parse_dates=["order_date"])
# Example 1: Create common durations for feature engineering
df["one_week_ago"] = df["order_date"] - timedelta(weeks=1)
df["projected_delivery"] = df["order_date"] + timedelta(days=14)
# Example 2: Calculate session duration
df["session_duration"] = timedelta(hours=2) # example fixed duration
# Example 3: Dynamic duration based on business logic
now = pd.Timestamp.now(tz="UTC")
df["hours_since_order"] = (now - df["order_date"]).dt.total_seconds() / 3600
3. Combining Multiple Units
# Complex duration
complex_delta = timedelta(
days=5,
hours=12,
minutes=45,
seconds=30,
microseconds=123456
)
print(complex_delta)
4. Best Practices in 2026
- Use
timedeltafor day/hour/minute/second arithmetic - For month/year calculations, combine with
relativedeltafromdateutil - Always perform arithmetic on timezone-aware datetimes
- Use pandas
Timedeltafor vectorized operations on large DataFrames - Keep duration constants at the top of your script for readability
Conclusion
Creating timedelta objects is the foundation for all time-based math in Python. In 2026 data science, you will use them daily for projections, freshness calculations, rolling windows, and feature engineering. Combine timedelta with timezone-aware datetime objects and pandas for clean, scalable, and accurate time arithmetic.
Next steps:
- Add timedelta-based features (days ago, projected dates, session duration, etc.) to one of your current datasets