Introduction to timedelta Objects in Python (10 Examples)


In this article, I’ll explain what timedelta objects are and illustrate how to handle and use timedelta objects in the Python programming language.

timedelta is a submodule of the datetime module, which provides the opportunity to work with datetime objects. timedelta objects are used to do mathematical operations in terms of date and time, and represent the difference between datetime objects.

The tutorial will consist of ten examples using timedelta objects. More precisely, the tutorial looks as follows:

So now the part you have been waiting for: the Python syntax.


Example Data & Importing Modules

Firstly, we need to import the datetime module and the humanize package.

from datetime import datetime, timedelta                    # importing datetime and timedelta modules
import humanize                                             # importing humanize module

Let’s also create some datetime objects in Python for the demonstration.

dt_1 = datetime(1984, 6, 10, 20, 45, 12)                    # generating sample datetime object
dt_2 = datetime(1996, 8, 18, 7, 35, 42)                     # generating sample datetime object
dt_1999_1_1 = datetime(1999, 1, 1)                          # generating sample datetime object
dt_1999_2_1 = datetime(1999, 2, 1)                          # generating sample datetime object


Example 1: Generating timedelta Objects

If you would like to create a timedelta object, you have two main options. Let’s have a look at both of them:

Construction Method

One of the ways to generate a timedelta object is using the timedelta constructor function, which provides the following parameters: weeks, days, hours, minutes, seconds, and microseconds.

The parameters are not bounded, in other words, the resulting total amount of time will be automatically normalized to the timedelta fields. For an example, see below.

td_1 = timedelta(weeks=5, days=25, hours=10, minutes=75, seconds=15)  # constructing timedelta object
print(td_1)                                                 # printing the timedelta object
# 60 days, 11:15:15

timedelta objects have 3 fields: days, seconds, and microseconds. See how the fields of td1 are printed out in the following script.

print(td_1.days, td_1.seconds, td_1.microseconds)
# 60 40515 0

If we called “td_1.hours” in our script, we would run into an error as “hours” is not a field in timedelta objects.

Subtraction Method

Another way to generate timedelta objects is subtraction. This operation returns a timedelta object which is equal to the time difference between two datetime objects. The sample data objects dt_1 and dt_2 are used for the demonstration, see below.

td_2 = dt_2 - dt_1
# 4451 days, 10:50:30

timedelta objects can also be negative, see the subtraction of dt_2 from dt_1 below.

td_3 = dt_1 - dt_2
# -4452 days, 13:09:30

You may learn more on how to get the time difference between two datetime objects here.


Example 2: Formatting by User-defined Function

By default, timedelta objects are in the format hh:mm:ss. If the days or microsecond fields have non-zero values, then they are expressed at the beginning and at the end respectively, see the difference between the display outputs below.

print(timedelta(hours=10, minutes=75, seconds=15))
print(timedelta(days=25, hours=10, minutes=75, seconds=15))
print(timedelta(days=25, hours=10, minutes=75, seconds=15, microseconds=500))
# 11:15:15
# 25 days, 11:15:15
# 25 days, 11:15:15.000500

However, if we need a customized format, then we can define our own function, as shown below.

def timedelta_formatter(td):                                # defining the function
    td_sec = td.seconds                                     # getting the seconds field of the timedelta
    hour_count, rem = divmod(td_sec, 3600)                  # calculating the total hours
    minute_count, second_count = divmod(rem, 60)            # distributing the rest to minutes and seconds
    msg = "The time difference is: {} days, {} hours, {} minutes, {} seconds".format(td.days,hour_count,minute_count,second_count)
    return msg                                              # returning the custom output
print(timedelta_formatter(td_1))                            # printing formatted output
# The time difference is: 60 days, 11 hours, 15 minutes, 15 seconds


Example 3: Formatting by humanize.naturaltime() Function

The humanize.naturaltime() function can be used to convert timedelta objects to phrases in English. The only downside is that it returns only an approximate time.

print(humanize.naturaltime(td_1))                           # printing formatted output
# a month ago
print(humanize.naturaltime(td_2))                           # printing formatted output
# 12 years ago

The function works with negative timedelta values as well, see below.

print(humanize.naturaltime(-td_2))                          # printing formatted output
# 12 years from now


Example 4: Adding timedelta Object to datetime Object

This example shows how to add a timedelta object to a datetime object. timedelta objects can be added to datetime objects to return new datetime objects.

For this example, we can use the previously generated objects dt_1 and td_1. See how the datetime object dt_3 is created by adding dt_1 to td_1 below.

print(dt_1)                                                 # printing datetime object
# 1984-06-10 20:45:12
print(td_1)                                                 # printing timedelta object
# 60 days, 11:15:15
dt_3 = dt_1 + td_1                                          # Adding timedelta object td_1 to datetime object dt_1
print(dt_3)                                                 # printing resulting datetime object
# 1984-08-10 08:00:27

You may add different time components to a datetime object. Learn here how to add seconds, minutes, and hours; and get more information here on how to add days, months, and years to a datetime object.


Example 5: Subtracting timedelta Object from datetime Object

In this example, I’ll explain how to subtract a timedelta object from a datetime object. For this example, we can use the previously generated objects dt_1 and td_1 (as we already did in the previous example).

See how the datetime object dt_4 is created by subtracting td_1 from dt_1 below.

dt_4 = dt_1 - td_1                                          # Subtracting timedelta object td_1 from datetime object dt_1
print(dt_4)                                                 # printing resulting datetime object
# 1984-04-11 09:29:57

Similar to the linked tutorials in the previous example, we do also provide articles on how to subtract seconds, minutes, and hours as well as days, months, and years.


Example 6: Subtracting timedelta Objects

This example illustrates how to conduct a subtraction between two timedelta objects. Let’s first create and print timedelta objects of 1 week and 30 days.

td_week = timedelta(weeks=1)                                # constructing a timedelta object of 1 week
print(td_week)                                              # printing the week timedelta object
# 7 days, 0:00:00
td_30_days = timedelta(days=30)                             # constructing a timedelta object of 30 days
print(td_30_days)                                           # printing the 30 days timedelta object
# 30 days, 0:00:00

Now it is time to subtract them from each other which returns another timedelta object.

td_diff = td_30_days - td_week                              # Subtracting timedelta object td_week from datetime object td_30_days
print(td_diff)                                              # printing the timedelta difference
# 23 days, 0:00:00

The previous syntax has created a new timedelta object called td_diff, which shows a difference of 23 days between our two input timedelta objects.


Example 7: Adding timedelta Objects

In this example, I’ll illustrate how to add two timedelta objects. For the demonstration, the previously constructed timedelta objects td_30_days and td_week are used.

td_sum = td_30_days + td_week                               # Adding timedelta object td_week to datetime object td_30_days
print(td_sum)                                               # printing the timedelta sum
# 37 days, 0:00:00

The time difference is 37 days in this example.


Example 8: Adding and Subtracting timedelta & datetime Objects in a Row

Example 8 explains how to combine addition and subtraction operations with datetime and timedelta objects in a single line of code. See td_combination below.

td_combination = dt_1999_1_1 - dt_1999_2_1 + td_30_days - td_week     # Generating the combined timedelta object
print(td_combination)                                       # printing the timedelta result
# -8 days, 0:00:00


Example 9: Converting timedelta Objects to Seconds

This example illustrates how to express timedelta objects in terms of seconds. We can utilize the total_seconds() function to implement it.

For this example, we’ll use the timedelta td_1 object that we have created previously.

print(td_1.total_seconds())                                 # printing timedelta object in terms of seconds
# 5224515.0


Example 10: Converting timedelta Objects to Other Time Units

To convert timedelta objects into other time units different from seconds, we can use the total_seconds() function first, and then convert the seconds into the time units of interest.

For instance, we can transform a timedelta object to hours as shown below.

td_30_days_in_sec = td_30_days.total_seconds()              # getting the total time in seconds
td_30_days_in_hours = td_30_days_in_sec / 3600              # converting total seconds to hours
print(td_30_days_in_hours)                                  # printing total hours
# 720.0

The same process can be repeated for other units as well by changing the divisor to the number of seconds in that time unit.

Let’s calculate a week count:

td_30_days_in_weeks = td_30_days_in_sec / (3600 * 24 * 7)   # converting total seconds to weeks
print(round(td_30_days_in_weeks, 2))                        # printing total weeks rounded to two decimals
# 4.29

On Statistics Globe, we provide more detailed tutorials on how to transform timedelta objects to other metrics such as minutes, hours, days, months, and years.


Video & Further Resources

Do you need further info on the Python programming syntax of this article? Then I recommend watching the following video on the Statistics Globe YouTube channel. In the video, I explain the examples of this tutorial:


The YouTube video will be added soon.


In addition, you could have a look at the other tutorials on this homepage. I have published several articles already:


Summary: In this Python programming tutorial, you have learned how to deal with timedelta objects. Don’t hesitate to tell me about it in the comments section below, in case you have any additional questions or comments.


Ömer Ekiz Python Programming & Informatics

This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get further information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.