Creating timedeltas

Dates And Time Mar 19, 2026

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 datetime or date for arithmetic
  • Pandas Timedelta for 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

# 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"])

# 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["order_date"] = df["order_date"].dt.tz_localize("UTC")   # demo dates are naive; make them UTC-aware to match now
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 timedelta for day/hour/minute/second arithmetic
  • For month/year calculations, combine with relativedelta from dateutil
  • Always perform arithmetic on timezone-aware datetimes
  • Use pandas Timedelta for vectorized operations on large DataFrames
  • Keep duration constants at the top of your script for readability

Building timedelta Objects

timedelta accepts weeks, days, hours, minutes, seconds, milliseconds and microseconds, and normalises them internally into days, seconds and microseconds. That is why timedelta(hours=36) prints as 1 day, 12:00:00.

timedeltas support arithmetic: they can be added, multiplied by numbers, divided by each other to get a ratio, and compared. pd.Timedelta and pd.to_timedelta provide the same features for pandas, including parsing strings like "1h30m".

There are no month or year units, because their length varies; use calendar-aware offsets for those.

Worked Example: Normalisation and Arithmetic

We create, combine and divide durations.

from datetime import timedelta
import pandas as pd

d = timedelta(hours=36)
print(d, d.days, d.seconds)

shift = timedelta(hours=7, minutes=30)
print(shift * 5)
print(timedelta(days=1) / shift)

print(pd.to_timedelta(["1h30m", "45min", "2 days"]).tolist())

36 hours is stored as 1 day plus 43,200 seconds. Five shifts of 7.5 hours make 1 day, 13:30:00, and one day equals 3.2 shifts. pandas parses the duration strings directly.

Practical Tips

Use descriptive constants such as GRACE_PERIOD = timedelta(days=3) instead of bare numbers in calculations. The intent becomes clear and the value is easy to change later.

When adding months, remember that pandas DateOffset(months=1) moves 31 January to the last day of February rather than failing, which is usually what billing logic expects. Check the rule with the business owner before relying on it.

Common Mistakes

  • Expecting .seconds to include days.
  • Looking for a months argument.
  • Parsing duration strings by hand.
  • Comparing durations as strings.

Quick Summary

  • timedelta normalises units.
  • Durations support arithmetic and division.
  • pd.to_timedelta parses strings.
  • Use calendar offsets for months.

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

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices