Skip to main content

Official Documentation & Resources

Primary Official Sources (REQUIRED)

Additional Authoritative Sources

IMPORTANT: Examples in this guide are adapted from the official Python documentation at https://docs.python.org/3/library/datetime.html

Overview

The timedelta class represents a duration, the difference between two dates or times. It stores the difference in terms of days, seconds, and microseconds internally, and can be used for date/time arithmetic. Timedelta objects are immutable and hashable.

A timedelta object represents a duration, the difference between two datetime or date instances to microsecond resolution.

Key Characteristics

  • Duration Representation: Represents a span of time, not a specific moment
  • Immutable Objects: Timedelta objects cannot be modified after creation
  • Thread Safety: Timedelta objects are immutable and therefore thread-safe
  • Arithmetic Support: Supports addition, subtraction, multiplication, and division
  • Internal Storage: Internally stores only days, seconds, and microseconds
  • Hashable: Can be used as dictionary keys and in sets
  • Precision: Microsecond precision (6 decimal places)

Prerequisites and Setup

Python Version Compatibility

  • Minimum Python version required: Python 2.3+ (datetime module introduction)

Installation and Imports

# Standard library (no installation needed)
from datetime import timedelta, datetime, date

# Alternative import
import datetime
# Then use: datetime.timedelta()

Basic Usage

Official Documentation Examples

Source: All examples adapted from https://docs.python.org/3/library/datetime.html#timedelta-objects

Simple Example

from datetime import timedelta, datetime

# Creating time durations (from official docs)
td = timedelta(days=7, hours=12, minutes=30)
print(f"Duration: {td}") # Duration: 7 days, 12:30:00

# Date arithmetic (from official docs)
now = datetime.now()
future = now + timedelta(days=30)
print(f"30 days from now: {future}")

# Time difference (from official docs)
start = datetime(2025, 1, 1)
end = datetime(2025, 6, 14)
difference = end - start
print(f"Days between: {difference.days}") # Days between: 164

Core Methods/Functions

from datetime import timedelta

# Constructor (from official docs)
td = timedelta(days=7, hours=12, minutes=30, seconds=45)
print(td) # 7 days, 12:30:45

# Total seconds (from official docs)
total = td.total_seconds()
print(f"Total seconds: {total}") # Total seconds: 690645.0

# Individual components (from official docs)
print(f"Days: {td.days}") # Days: 7
print(f"Seconds: {td.seconds}") # Seconds: 45045

Common Patterns

# Pattern 1: Time intervals (from official docs)
from datetime import timedelta

one_hour = timedelta(hours=1)
one_day = timedelta(days=1)
one_week = timedelta(weeks=1)

# Pattern 2: Calculations (from official docs)
meeting_duration = timedelta(hours=1, minutes=30)
break_time = timedelta(minutes=15)
total_time = meeting_duration + break_time

# Pattern 3: Comparisons (from official docs)
short_break = timedelta(minutes=5)
long_break = timedelta(minutes=15)
print(f"Short break < Long break: {short_break < long_break}")

timedelta API Reference

Constructor

MethodDescriptionParametersReturn TypeExample
timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)Create a timedelta objectAll optional, default to 0timedeltatimedelta(days=7, hours=12)

Instance Methods

MethodDescriptionReturn TypeExample
total_seconds()Total seconds as floatfloattd.total_seconds()

Properties and Attributes

AttributeDescriptionTypeRangeExample
daysNumber of daysint-999999999 to 999999999td.days
secondsSeconds (0-86399)int0-86399td.seconds
microsecondsMicroseconds (0-999999)int0-999999td.microseconds

Class Attributes

AttributeDescriptionValueExample
minMinimum timedelta valuetimedelta(-999999999)timedelta.min
maxMaximum timedelta valuetimedelta(999999999, 86399, 999999)timedelta.max
resolutionSmallest possible differencetimedelta(microseconds=1)timedelta.resolution

Detailed Method Examples

Creating timedelta Objects (from official docs)

from datetime import timedelta

# Various units (from official docs)
td1 = timedelta(days=7)
print(td1) # 7 days, 0:00:00

td2 = timedelta(hours=12)
print(td2) # 12:00:00

td3 = timedelta(minutes=30)
print(td3) # 0:30:00

td4 = timedelta(seconds=45)
print(td4) # 0:00:45

td5 = timedelta(microseconds=123456)
print(td5) # 0:00:00.123456

# Combined units (from official docs)
td_combined = timedelta(days=7, hours=12, minutes=30, seconds=45, microseconds=123456)
print(td_combined) # 7 days, 12:30:45.123456

# Using weeks (from official docs)
td_weeks = timedelta(weeks=2)
print(td_weeks) # 14 days, 0:00:00

# Using milliseconds (from official docs)
td_millis = timedelta(milliseconds=1500)
print(td_millis) # 0:00:01.500000

Timedelta Arithmetic (from official docs)

from datetime import timedelta

td1 = timedelta(days=7, hours=12)
td2 = timedelta(days=3, hours=6)

# Addition (from official docs)
total = td1 + td2
print(f"Total: {total}") # Total: 10 days, 18:00:00

# Subtraction (from official docs)
difference = td1 - td2
print(f"Difference: {difference}") # Difference: 4 days, 6:00:00

# Multiplication (from official docs)
doubled = td1 * 2
print(f"Doubled: {doubled}") # Doubled: 15 days, 0:00:00

# Division (from official docs)
halved = td1 / 2
print(f"Halved: {halved}") # Halved: 3 days, 18:00:00

# Floor division (from official docs)
quotient = td1 // td2
print(f"Quotient: {quotient}") # Quotient: 2

# Modulo (from official docs)
remainder = td1 % td2
print(f"Remainder: {remainder}") # Remainder: 1 day, 0:00:00

Date/Datetime Arithmetic (from official docs)

from datetime import datetime, date, timedelta

# Datetime arithmetic (from official docs)
dt = datetime(2025, 6, 14, 12, 30, 45)
one_week = timedelta(weeks=1)

future_dt = dt + one_week
print(f"One week later: {future_dt}") # One week later: 2025-06-21 12:30:45

past_dt = dt - one_week
print(f"One week ago: {past_dt}") # One week ago: 2025-06-07 12:30:45

# Date arithmetic (from official docs)
d = date(2025, 6, 14)
one_month = timedelta(days=30)

future_date = d + one_month
print(f"30 days later: {future_date}") # 30 days later: 2025-07-14

# Time differences (from official docs)
start = datetime(2025, 1, 1, 0, 0, 0)
end = datetime(2025, 6, 14, 12, 30, 45)
duration = end - start
print(f"Duration: {duration}") # Duration: 164 days, 12:30:45

Converting to Total Units (from official docs)

from datetime import timedelta

td = timedelta(days=7, hours=12, minutes=30, seconds=45)

# Total seconds (from official docs)
total_seconds = td.total_seconds()
print(f"Total seconds: {total_seconds}") # Total seconds: 690645.0

# Convert to other units
total_minutes = total_seconds / 60
print(f"Total minutes: {total_minutes}") # Total minutes: 11510.75

total_hours = total_seconds / 3600
print(f"Total hours: {total_hours}") # Total hours: 191.845833...

total_days = total_seconds / 86400
print(f"Total days: {total_days}") # Total days: 7.993...

Timedelta Components (from official docs)

from datetime import timedelta

# Large timedelta (from official docs)
td = timedelta(days=50, hours=27, minutes=90, seconds=120)

# Python normalizes the values (from official docs)
print(f"Normalized: {td}") # Normalized: 51 days, 5:32:00
print(f"Days: {td.days}") # Days: 51
print(f"Seconds: {td.seconds}") # Seconds: 19920 (5 hours, 32 minutes in seconds)
print(f"Microseconds: {td.microseconds}") # Microseconds: 0

# Breakdown calculation
hours = td.seconds // 3600
minutes = (td.seconds % 3600) // 60
seconds = td.seconds % 60
print(f"Breakdown: {td.days} days, {hours} hours, {minutes} minutes, {seconds} seconds")

Timedelta Comparison (from official docs)

from datetime import timedelta

td1 = timedelta(hours=24)
td2 = timedelta(days=1)
td3 = timedelta(hours=25)

# Equality (from official docs)
print(f"24 hours == 1 day: {td1 == td2}") # True

# Comparison (from official docs)
print(f"24 hours < 25 hours: {td1 < td3}") # True
print(f"1 day > 25 hours: {td2 > td3}") # False

# Sorting timedeltas (from official docs)
durations = [timedelta(hours=3), timedelta(days=1), timedelta(minutes=30)]
sorted_durations = sorted(durations)
print(f"Sorted: {sorted_durations}")

Working with Negative Timedeltas (from official docs)

from datetime import timedelta, datetime

# Negative timedelta (from official docs)
negative_td = timedelta(days=-7)
print(f"Negative: {negative_td}") # Negative: -7 days, 0:00:00

# Absolute value (from official docs)
abs_td = abs(negative_td)
print(f"Absolute: {abs_td}") # Absolute: 7 days, 0:00:00

# Subtracting larger from smaller (from official docs)
dt1 = datetime(2025, 6, 14)
dt2 = datetime(2025, 6, 21)
diff = dt1 - dt2 # Earlier - Later = Negative
print(f"Difference: {diff}") # Difference: -7 days, 0:00:00

Class Attributes (from official docs)

from datetime import timedelta

# Minimum and maximum values (from official docs)
print(f"Minimum timedelta: {timedelta.min}") # Minimum timedelta: -999999999 days, 0:00:00
print(f"Maximum timedelta: {timedelta.max}") # Maximum timedelta: 999999999 days, 23:59:59.999999

# Resolution (from official docs)
print(f"Resolution: {timedelta.resolution}") # Resolution: 0:00:00.000001

# Practical examples
one_microsecond = timedelta.resolution
print(f"One microsecond: {one_microsecond}")

very_long = timedelta.max
print(f"Very long duration: {very_long.total_seconds()} seconds")

Important Notes

Gotchas and Common Pitfalls

  • Timedelta objects are immutable - operations return new objects
  • Internal storage uses only days, seconds, and microseconds (other units are converted)
  • Seconds attribute only shows the seconds component (0-86399), not total seconds
  • Division can result in float timedelta objects
  • Large values may cause overflow errors

Internal Storage Normalization

from datetime import timedelta

# Python normalizes input values (from official docs)
td = timedelta(hours=25, minutes=90)
print(f"Normalized: {td}") # Normalized: 1 day, 2:30:00

# Breakdown of internal storage
print(f"Days: {td.days}") # Days: 1
print(f"Seconds: {td.seconds}") # Seconds: 9000 (2.5 hours in seconds)
print(f"Microseconds: {td.microseconds}") # Microseconds: 0

Error Handling

from datetime import timedelta

# Overflow handling (from official docs)
try:
huge_td = timedelta(days=1000000000) # Exceeds maximum
except OverflowError as e:
print(f"Error: {e}")

# Division by zero
try:
td = timedelta(days=1)
result = td / 0
except ZeroDivisionError as e:
print(f"Error: {e}")

Performance Considerations

  • Timedelta objects are efficient for arithmetic operations
  • Converting between units requires calculation
  • Use total_seconds() instead of manual conversion when possible
  • Avoid unnecessary object creation in loops

Best Practices

  1. Use total_seconds() for conversion - More accurate than manual calculation
  2. Understand internal storage - Only days, seconds, microseconds are stored
  3. Handle negative timedeltas - Can result from date/time subtraction
  4. Use appropriate units - Choose the most natural unit for your use case
  5. Consider precision - Microsecond precision may not always be needed
  6. Cache commonly used timedeltas - Create once and reuse
  7. Use timedelta for scheduling - Ideal for recurring intervals
  • datetime.datetime - For date/time arithmetic
  • datetime.date - For date arithmetic
  • datetime.time - Time objects (no arithmetic support)
  • Main datetime module - Complete module overview