Content · Programming · Python

Python datetime.timedelta Class: Calculate Time Differences

Add and subtract timedeltas to perform calendar-independent duration arithmetic.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Add and subtract timedeltas to perform calendar-independent duration arithmetic.

How It Works


datetime.timedelta stores durations in days, seconds, and microseconds, and normalizes fields internally. For true elapsed time across daylight-saving boundaries, work with UTC instants rather than naive local wall-clock arithmetic.

Step-by-Step Example


from datetime import datetime, timedelta, timezone
started_at = datetime(2026, 10, 17, 10, tzinfo=timezone.utc)
finished_at = started_at + timedelta(hours=2, minutes=30)
print(finished_at.isoformat())
print((finished_at - started_at).total_seconds())

Understanding the Example


  • The expression 'datetime(2026, 10, 17, 10, tzinfo=timezone.utc)' supplies the value stored as 'started_at'. This value is then used or checked by the later statements.
  • The expression 'started_at + timedelta(hours=2, minutes=30)' supplies the value stored as 'finished_at'. This value is then used or checked by the later statements.

A successful run of this example prints the following output:

2026-10-17T12:30:00+00:00
9000.0

Where This Fits in a Real Program


For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.

Practice: Try It Yourself


Use total_seconds() to include days and fractional seconds.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Reading timedelta.seconds as the total number of elapsed seconds when days are present.
  • Calculate a task deadline 90 minutes after a specified UTC start time.

Key Takeaways


  • Add and subtract timedeltas to perform calendar-independent duration arithmetic.
  • datetime.timedelta stores durations in days, seconds, and microseconds, and normalizes fields internally.
  • Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.
Share this resourceSend this page to someone who may find it useful.