PYnative

Practice Coding

  • Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQs▼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilers▼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Python DateTime » Timedelta in Python

Timedelta in Python

Updated on: December 1, 2026 | 4 Comments

In this tutorial, you’ll learn what a timedelta is in Python and how to use it to do date and time arithmetic.

This article is part of a series on Python Date and Time.

After reading this article, you’ll learn:

  • How to calculate the difference between two datetimes using timedelta.
  • How to calculate future and past dates by adding or subtracting weeks, days, hours, minutes, or seconds.
  • The timedelta attributes and methods, such as days, seconds, and total_seconds().
  • How to add, subtract, multiply, divide, and compare timedelta objects.
  • How to format a timedelta as a string and convert a string to a timedelta.

Table of contents

  • What is Timedelta in Python?
    • TimeDelta Object
    • TimeDelta Attributes
  • TimeDelta with Weeks
  • Time Delta with Seconds and MicroSeconds
    • TimeDelta to Seconds
  • Time Delta with Days
  • TimeDelta with Hours
  • Add or Subtract Two timedelta Objects
  • Compare two TimeDelta
  • Formatting a Timedelta
    • Convert String to TimeDelta
  • Add Months and Years
  • Summary

What is Timedelta in Python?

A timedelta represents a duration: the difference between two dates, times, or datetimes, with a precision of one microsecond. For example, “3 days and 4 hours” or “90 minutes” are durations.

The timedelta class is part of Python’s datetime module. You use it to add or subtract weeks, days, hours, minutes, seconds, milliseconds, and microseconds from a date or datetime. You also get a timedelta whenever you subtract one datetime from another.

Import the timedelta class from the datetime module, and you’re ready to use it:

from datetime import timedeltaCode language: Python (python)
Add Days to Date using timedelta
Add Days to Date using timedelta

Example 1: Calculate the difference between two dates

from datetime import datetime

start = datetime(2020, 3, 21, 12, 30)
end = datetime(2021, 7, 4, 9, 9, 37)

# subtracting two datetimes gives a timedelta
duration = end - start

print(duration)
print(type(duration))Code language: Python (python)

Output:

469 days, 20:39:37
<class 'datetime.timedelta'>

The result means 469 days, 20 hours, 39 minutes, and 37 seconds.

Example 2: Calculate a future date

Let’s use timedelta to add four weeks to a date:

from datetime import datetime, timedelta

given_date = datetime(2021, 7, 4, 5, 41, 46)
print('Given Date:', given_date)

new_date = given_date + timedelta(weeks=4)
print('Future Date:', new_date)Code language: Python (python)

Output:

Given Date: 2021-07-04 05:41:46
Future Date: 2021-08-01 05:41:46

In the examples we use fixed dates so your output matches ours. Replace them with datetime.now() to calculate from the current date and time.

TimeDelta Object

You create a timedelta object with the timedelta() constructor. It accepts seven keyword arguments:

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)Code language: Python (python)
  • All seven arguments are optional, and the default value is 0.
  • They can be integers or floats, positive or negative. For example, timedelta(hours=1.5) is 1 hour and 30 minutes.
from datetime import timedelta

sample = timedelta(
    days=40,
    seconds=3,
    microseconds=2,
    milliseconds=1200,
    minutes=3,
    hours=23,
    weeks=3
)

# all values are combined into days, seconds, and microseconds
print(sample)
print(repr(sample))Code language: Python (python)

Output:

61 days, 23:03:04.200002
datetime.timedelta(days=61, seconds=82984, microseconds=200002)

Here, 3 weeks plus 40 days is 61 days, and 1200 milliseconds is 1.2 seconds.

Note: Internally, a timedelta stores only days, seconds, and microseconds. Python converts every other unit into these: 1 week becomes 7 days, 1 hour becomes 3600 seconds, 1 minute becomes 60 seconds, and 1 millisecond becomes 1000 microseconds. This is called normalization.

After normalization, each stored value stays within these ranges:

AttributeRange (inclusive)
days-999999999 to 999999999
seconds0 to 86399 (the number of seconds in a day, minus one)
microseconds0 to 999999
timedelta range

If the number of days falls outside this range, Python raises an OverflowError. The seconds and microseconds always stay in range because extra seconds are carried over into days.

TimeDelta Attributes

You can read the parts of a timedelta through its attributes. They’re useful when you calculate the difference between two dates and need the result in days or seconds.

Attribute / methodMeaning
td.daysThe number of whole days
td.secondsThe remaining seconds after the days (0 to 86399), not the total seconds
td.microsecondsThe remaining microseconds (0 to 999999)
td.total_seconds()The whole duration in seconds, as a float
timedelta.maxThe largest positive timedelta: timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)
timedelta.minThe most negative timedelta: timedelta(-999999999)
timedelta.resolutionThe smallest possible difference between two timedeltas: 1 microsecond
Timedelta Attribute

Example:

from datetime import datetime

d1 = datetime(2020, 3, 21, 12, 30)
d2 = datetime(2021, 1, 12, 18, 15)

td = d2 - d1
print("Timedelta:", td)

print("Days:", td.days)
print("Seconds:", td.seconds)
print("Microseconds:", td.microseconds)
print("Total seconds:", td.total_seconds())

print("Max:", td.max)
print("Min:", td.min)
print("Resolution:", td.resolution)Code language: Python (python)

Output:

Timedelta: 297 days, 5:45:00
Days: 297
Seconds: 20700
Microseconds: 0
Total seconds: 25681500.0
Max: 999999999 days, 23:59:59.999999
Min: -999999999 days, 0:00:00
Resolution: 0:00:00.000001

Note: A common mistake is to use td.seconds as the total number of seconds. Here it’s only 20700 (5 hours 45 minutes), because the 297 days are stored separately. Use total_seconds() for the whole duration.

TimeDelta with Weeks

Use the weeks argument to add or subtract weeks from a date. Add a timedelta to get a future date, and subtract it to get a past date.

Example:

from datetime import datetime, timedelta

current_date = datetime(2021, 7, 4, 7, 4, 19)
print("Current Date and Time:", current_date)

# subtract 6 weeks
past_date = current_date - timedelta(weeks=6)
print("6 weeks before:", past_date)

# add 2 weeks
future_date = current_date + timedelta(weeks=2)
print("2 weeks later:", future_date)Code language: Python (python)

Output:

Current Date and Time: 2021-07-04 07:04:19
6 weeks before: 2021-05-23 07:04:19
2 weeks later: 2021-07-18 07:04:19

Time Delta with Seconds and MicroSeconds

Use the seconds, milliseconds, and microseconds arguments to calculate a time a few seconds or milliseconds before or after a given time.

from datetime import datetime, timedelta

current_date = datetime(2021, 7, 4, 7, 8, 22, 651620)
print("Current Date and Time:", current_date)

# add 60 seconds
print("60 seconds after:", current_date + timedelta(seconds=60))

# subtract 500 milliseconds
print("500 milliseconds before:", current_date - timedelta(milliseconds=500))Code language: Python (python)

Output:

Current Date and Time: 2021-07-04 07:08:22.651620
60 seconds after: 2021-07-04 07:09:22.651620
500 milliseconds before: 2021-07-04 07:08:22.151620

TimeDelta to Seconds

The total_seconds() method returns the whole duration in seconds as a float, accurate to the microsecond. (For extremely long durations, over about 270 years, the float can lose microsecond accuracy.)

To convert a timedelta to minutes or hours, divide the total seconds by 60 or 3600. You can also divide by another timedelta, which gives the same result:

from datetime import timedelta

td = timedelta(hours=2, minutes=30)

print("Seconds:", td.total_seconds())
print("Minutes:", td.total_seconds() / 60)
print("Hours:", td.total_seconds() / 3600)

# dividing by a timedelta
print("Hours:", td / timedelta(hours=1))
print("Whole hours:", td // timedelta(hours=1))Code language: Python (python)

Output:

Seconds: 9000.0
Minutes: 150.0
Hours: 2.5
Hours: 2.5
Whole hours: 2

Time Delta with Days

Pass the number of days to timedelta() and add it to or subtract it from a date to get a future or past date. This also works with date objects:

from datetime import date, timedelta

today = date(2021, 7, 4)
print("Given date:", today)

print("100 days later:", today + timedelta(days=100))
print("100 days before:", today - timedelta(days=100))
print("Tomorrow:", today + timedelta(days=1))
print("Yesterday:", today - timedelta(days=1))Code language: Python (python)

Output:

Given date: 2021-07-04
100 days later: 2021-10-12
100 days before: 2021-03-26
Tomorrow: 2021-07-05
Yesterday: 2021-07-03

Python handles month lengths and leap years for you, so adding days always gives a valid date.

TimeDelta with Hours

Use the hours argument to calculate a time some hours before or after a given time. If the result crosses midnight, the date changes too:

from datetime import datetime, timedelta

current = datetime(2021, 7, 4, 7, 16, 31)
print("Current time:", current)

print("12 hours later:", current + timedelta(hours=12))
print("9 hours before:", current - timedelta(hours=9))
print("90 minutes later:", current + timedelta(hours=1.5))Code language: Python (python)

Output:

Current time: 2021-07-04 07:16:31
12 hours later: 2021-07-04 19:16:31
9 hours before: 2021-07-03 22:16:31
90 minutes later: 2021-07-04 08:46:31

Add or Subtract Two timedelta Objects

You can add or subtract two timedelta objects to get a new timedelta. This is useful when a duration is made of several parts.

For example, suppose a report is due in 2 weeks and 2 days, plus a 12 hour 30 minute review period:

from datetime import datetime, timedelta

current_date = datetime(2021, 7, 4, 7, 29, 12)
print("Current date:", current_date)

td1 = timedelta(weeks=2, days=2)
td2 = timedelta(hours=12, minutes=30)

# add two timedeltas
total = td1 + td2
print("Total duration:", total)
print("Report due:", current_date + total)

# subtract two timedeltas
diff = td1 - td2
print("Difference:", diff)
print("Date:", current_date - diff)Code language: Python (python)

Output:

Current date: 2021-07-04 07:29:12
Total duration: 16 days, 12:30:00
Report due: 2021-07-20 19:59:12
Difference: 15 days, 11:30:00
Date: 2021-06-18 19:59:12

Besides adding and subtracting, you can also use these operations with timedelta objects:

  • Multiply by a number: td * 2.5. The result is rounded to the nearest microsecond.
  • Divide by a number: td / 3 gives a timedelta.
  • Divide by a timedelta: td1 / td2 gives a float, and td1 // td2 gives an integer.
  • Modulo: td1 % td2 gives the remainder as a timedelta.
  • Negate and absolute value: -td and abs(td).
from datetime import timedelta

td1 = timedelta(days=365)

td2 = 2.5 * td1
print("Multiply:", td2)

print("Divide by number:", td1 / 4)
print("How many weeks:", td1 // timedelta(weeks=1))
print("Modulo:", td2 % td1)

negative = timedelta(hours=-3)
print("Negative:", negative)
print("Absolute:", abs(negative))Code language: Python (python)

Output:

Multiply: 912 days, 12:00:00
Divide by number: 91 days, 6:00:00
How many weeks: 52
Modulo: 182 days, 12:00:00
Negative: -1 day, 21:00:00
Absolute: 3:00:00

A negative timedelta is shown as negative days plus positive hours: -3 hours is -1 day, 21:00:00 (minus one day, plus 21 hours).

Compare two TimeDelta

Use the comparison operators (==, !=, <, >, <=, >=) to compare two timedelta objects. The longer duration is the greater one.

  • == and != work with any object. Comparing a timedelta with a number simply returns False for ==.
  • < and > work only between timedeltas. Comparing a timedelta with a number raises a TypeError.
from datetime import timedelta

d1 = timedelta(hours=57)
d2 = timedelta(hours=25, seconds=2)

print(d2 != d1)
print(d1 > d2)
print(timedelta(hours=24) == timedelta(days=1))
print(d2 == 25)

# comparing with a number raises an error
print(d2 > 5)Code language: Python (python)

Output:

True
True
True
False
TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int'

To compare a timedelta with a number of hours or seconds, convert one side first, for example d2 > timedelta(hours=5) or d2.total_seconds() > 5 * 3600.

Formatting a Timedelta

A timedelta has no strftime() method. Converting it with str() (or printing it) gives the format [D day[s], ]H:MM:SS[.UUUUUU]. For a custom format such as HH:MM:SS or “2 days 3 hours”, split the duration yourself with divmod():

from datetime import timedelta

td = timedelta(days=2, hours=3, minutes=7, seconds=4)
print("Default:", td)

total = int(td.total_seconds())
hours, rem = divmod(total, 3600)
minutes, seconds = divmod(rem, 60)
print(f"HH:MM:SS: {hours:02d}:{minutes:02d}:{seconds:02d}")

print(f"Readable: {td.days} days {td.seconds // 3600} hours {td.seconds % 3600 // 60} minutes")Code language: Python (python)

Output:

Default: 2 days, 3:07:04
HH:MM:SS: 51:07:04
Readable: 2 days 3 hours 7 minutes

To learn more ways of formatting durations, see convert seconds to hh:mm:ss in Python.

A datetime that you calculated with a timedelta is a normal datetime, so you format it with strftime():

from datetime import datetime, timedelta

present_date = datetime(2021, 7, 4, 7, 54, 59)
later = present_date + timedelta(days=20)

print("Formatted:", later.strftime('%d/%m/%Y %I:%M:%S %p'))Code language: Python (python)

Output:

Formatted: 24/07/2021 07:54:59 AM

Convert String to TimeDelta

To convert a duration string such as "08:35:45" to a timedelta, split it into hours, minutes, and seconds and pass them to timedelta():

from datetime import timedelta

duration_str = '08:35:45'
hours, minutes, seconds = map(int, duration_str.split(':'))

td = timedelta(hours=hours, minutes=minutes, seconds=seconds)
print(td)
print(td.total_seconds())Code language: Python (python)

Output:

8:35:45
30945.0

You can also parse the string with strptime() and use the time parts of the result:

from datetime import datetime, timedelta

t = datetime.strptime('08:35:45', '%H:%M:%S')
td = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
print(td)Code language: Python (python)

Output:

8:35:45

The strptime() method only works for durations under 24 hours, because the hour must be between 0 and 23. The split() method works for any number of hours.

Display timedelta in string format

  • str(td) gives the readable form, such as 34 days, 0:08:04. print() uses it automatically.
  • repr(td) gives the constructor form, such as datetime.timedelta(days=34, seconds=484), which is useful for debugging.

Example:

from datetime import timedelta

td = timedelta(days=34, minutes=7, seconds=64)

print(str(td))
print(repr(td))Code language: Python (python)

Output:

34 days, 0:08:04
datetime.timedelta(days=34, seconds=484)

Add Months and Years

A timedelta has no months or years argument, because months and years don’t have a fixed length. Adding timedelta(days=30) isn’t always “one month later”. To add calendar months or years, use relativedelta from the third-party dateutil library (pip install python-dateutil):

from datetime import date, timedelta
from dateutil.relativedelta import relativedelta

d = date(2021, 1, 31)

print("+30 days:", d + timedelta(days=30))
print("+1 month:", d + relativedelta(months=1))
print("+1 year:", d + relativedelta(years=1))Code language: Python (python)

Output:

+30 days: 2021-03-02
+1 month: 2021-02-28
+1 year: 2022-01-31

relativedelta moves to the same day in the next month and, if that day doesn’t exist, uses the last day of the month (28 February here). See difference between two dates in months and years for more.

Summary

TaskUse
Create a durationtimedelta(days=2, hours=3)
Difference between two datetimesdt2 - dt1
Future or past datedt + timedelta(days=n), dt - timedelta(weeks=n)
Total secondstd.total_seconds()
Duration in hourstd / timedelta(hours=1)
Compare durationstd1 > td2
Add months or yearsdt + relativedelta(months=1)

Filed Under: Python, Python DateTime

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python DateTime

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Somebody says

    October 6, 2024 at 12:11 pm

    Thanks for the article.
    You mention timedelta instances can’t be compared using “” operators.
    Fine… but we’re left in the void because you do not provide the alternative way of doing it…

    Reply
  2. mba1398 says

    September 17, 2022 at 3:57 pm

    hi,

    why the para in the first picture is 6 while it’s meaning is 5?

    Reply
  3. Rick says

    November 30, 2021 at 9:06 pm

    You say “a millisecond will be converted to 1000 seconds” but it should say 1000 microseconds.
    In section “TimeDelta Object” you say “It returns a timedetlta object”.
    The section “Formatting a Timedelta” is actually formatting a datetime, not a timedelta.
    The section “Convert String to TimeDelta” is converting to datetime, not timedelta.

    Reply
    • Ricardo Sanchez says

      January 18, 2023 at 8:59 pm

      L

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python DateTime
TweetF  sharein  shareP  Pin

 Python DateTime

  • Python DateTime Guide
  • Python Get Current DateTime
  • Python DateTime Formatting
  • Python String to DateTime
  • Python Timestamp
  • Python Timedelta
  • Python TimeZones
  • List All TimeZones in Python

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com