HomeTutorialsPython

# Python timedelta: Working With Time Intervals in Python

In Python, timedelta is a data type within the datetime module used to represent durations or differences between two points in time.
Jun 2024  · 9 min read

Many real-world datasets include dates and times, and a common operation in data science is to calculate the time difference between two points in time.

The units we use to measure dates and times (years, months, days, hours, minutes, seconds) are not the easiest to work with, especially when these units have irregular lengths.

However, Python's `timedelta` data type, which is part of the `datetime` module, deals with the complexities of working out time intervals.

Let’s start with a very short answer on what is Python’s `timedelta` and then continue with more details.

To learn more about dates and times in Python, check out this course on Working With Dates and Time in Python.

## Short Answer: What Is Python's timedelta

The two most important and frequently used data types from the `datetime` module are `timedelta` and `datetime`. While `datetime` objects represent specific points in time (e.g., January 1st, 2024 at 10:30 AM), `timedelta` objects represent durations or intervals between two points. Think of it as the difference between asking "When?" (`datetime`) and "How long?" (`timedelta`).

Consider two dates, which we can represent using two `datetime` objects. Subtracting one date from another creates a `timedelta` object representing the time interval between the dates :

``````import datetime

first_date = datetime.datetime(year=2024, month=1, day=1)
second_date = datetime.datetime(year=2024, month=5, day=27)
interval = second_date - first_date
print(interval)``````
``147 days, 0:00:00``

The output shows the two dates are exactly 147 days apart. In the following example, we use the date and time when the code is executed by calling datetime.datetime.now():

``````first_date = datetime.datetime(year=2024, month=1, day=1)
second_date = datetime.datetime.now()
interval = second_date - first_date

print(second_date)
print(interval)``````
``````2024-05-28 08:32:44.871646
148 days, 8:32:44.871646``````

The `timedelta` object now shows the time elapsed between the start of 2024 and the date and time when the code is executed.

We'll explore Python's `timedelta` further in this article.

## Creating timedelta Objects

In the previous section, we created a `timedelta` object from two `datetime` objects, but we can also create a time interval directly by calling the `timedelta()` constructor:

``````interval = datetime.timedelta(days=10, seconds=3600)
print(interval)``````
``10 days, 1:00:00``

The interval is ten days and one hour long. We can also use other time units when creating a `timedelta` instance:

``````interval = datetime.timedelta(weeks=1, days=3, hours=1)
print(interval)``````
``10 days, 1:00:00``

Any of the following time units are valid when calling `timedelta()`:

• weeks
• days
• hours
• minutes
• seconds
• milliseconds
• microseconds

This tutorial will dive deeper into how time intervals are stored in a `timedelta` object.

## Basic Arithmetic With timedelta

We can also perform arithmetic operations with `timedelta` objects. Consider the following three `datetime` objects, representing the release dates for Python 1.0, Python 2.0, and Python 3.0. Subtracting `datetime` objects from each other creates a `timedelta` object:

``````release_date_python_1 = datetime.datetime(year=1991, month=2, day=20)
release_date_python_2 = datetime.datetime(year=2000, month=10, day=16)
release_date_python_3 = datetime.datetime(year=2008, month=12, day=3)

​time_between_1_and_2 = release_date_python_2 - release_date_python_1
time_between_2_and_3 = release_date_python_3 - release_date_python_2

​print(time_between_1_and_2)
print(time_between_2_and_3)``````
``````3526 days, 0:00:00
2970 days, 0:00:00``````

The output shows the number of days between the releases of Python 1.0 and 2.0 and between the releases of Python 2.0 and 3.0. The time intervals are `timedelta` objects.

It's also possible to perform addition and subtraction between `timedelta` objects and `datetime` objects. Let's add a `timedelta` with `days=100` to `release_date_python_3`:

``print(release_date_python_3 + datetime.timedelta(days=100))``
``2009-03-13 00:00:00``

Python 3.0 was released on December 3, 2008. Adding one hundred days to this date takes us to March 13, 2009.

However, we can also perform arithmetic operations directly with `timedelta` objects:

``````print("Difference between gap 1 and gap 2")
print(time_between_1_and_2 - time_between_2_and_3)

print("Sum of gap 1 and gap 2")
print(time_between_1_and_2 + time_between_2_and_3)``````
``````Difference between gap 1 and gap 2
556 days, 0:00:00

Sum of gap 1 and gap 2
6496 days, 0:00:00``````

The output confirms it's possible to subtract and add `timedelta` objects. Multiplication and division are also possible:

``````print("Multiply time interval by 3:")
print(time_between_1_and_2 * 3)

print("Divide time interval by 3:")
print(time_between_1_and_2 / 3)``````
``````Multiply time interval by 3:
10578 days, 0:00:00

Divide time interval by 3:
1175 days, 8:00:00``````

We can also compare `timedelta` objects:

``````print("Check if gap 1 is greater than gap 2")
print(time_between_1_and_2 > time_between_2_and_3)``````
``True``

The output confirms that the interval between the release dates of Python 1.0 and Python 2.0 is longer than the interval between Python 2.0 and Python 3.0.

## Key timedelta Attributes and Methods

A `timedelta` object represents a time interval by storing the number of days, seconds and microseconds. These three units are the only time units represented by attributes in the `timedelta` class:

``````interval = datetime.timedelta(
weeks=1,
hours=10,
minutes=22,
milliseconds=1042,
)

print(f"{interval = }")
print(f"{interval.days = }")
print(f"{interval.seconds = }")
print(f"{interval.microseconds = }")``````
``````interval = datetime.timedelta(days=7, seconds=37321, microseconds=42000)
interval.days = 7
interval.seconds = 37321
interval.microseconds = 42000``````

Even though the call to `timedelta()` includes arguments for weeks, hours, minutes, and milliseconds, the constructor converts these units to days, seconds, and microseconds. The `print()` calls include f-strings with an equals sign = to display the variable name and its value. You can learn more about f-strings in this tutorial on f-string formatting in Python.

Another useful tool of the `timedelta` class is the `total_seconds()` method. This method returns the total time interval in seconds:

``````print("Total time interval in seconds:")
print(interval.total_seconds())``````
``````Total time interval in seconds:
642121.042``````

This value represents the entire time interval in seconds. It's not the same as the value of `.seconds`, which only shows the seconds component of the interval without accounting for the days and microseconds.

We can use the value returned by `.total_seconds()` to convert the time interval into any other unit:

``````print("Total time interval in days:")
print(interval.total_seconds() / 3600 / 24)``````
``````Total time interval in days:
7.431956504629629``````

The output shows the time interval in days since the value returned by `.total_seconds()` is divided by the number of seconds in an hour and the number of hours in a day.

## timedelta Example: Calculating Growth

Let's look at an example. A company's online store that sells Python books logs all the sales. Here's the data for one customer:

``````data = {
"customer_id": 3542,
"sales": [
{"date": "2024-04-21T13:23:45", "price": 24.99, "quantity": 1},
{"date": "2024-02-13T10:54:12", "price": 24.99, "quantity": 2},
{"date": "2024-01-08T20:32:24", "price": 18.99, "quantity": 1},
],
}
``````

We need to calculate the time difference between the first and last orders of a customer. The orders are always in chronological order in the list containing all the sales.

Our first step is to extract the dates from this nested structure and convert them into `datetime` objects. Thankfully, the timestamps are in the standard ISO 8601 format (YYYY-MM-DDTHH:MM:SS), so we can use the convenient `fromisoformat()` method:

``````sales = data["sales"]
dates = []
for item in sales:
date = datetime.datetime.fromisoformat(item["date"])
dates.append(date)

print(dates)
``````
``[datetime.datetime(2024, 4, 21, 13, 23, 45), datetime.datetime(2024, 2, 13, 10, 54, 12), datetime.datetime(2024, 1, 8, 20, 32, 24)]``

The list `dates` contains `datetime` objects with the dates of each order. Finally, we can calculate the time interval between the first and last order:

``````time_span = dates[0] - dates[-1]
print(time_span)
print(time_span.days)``````
``````103 days, 16:51:21
103``````

The difference between the first and last dates gives a `timedelta` object. The code displays `time_span`, which shows the number of days, hours, minutes, and seconds. We also display `time_span.days` to show just the whole number of days.

If you want to learn more about converting strings to datetime, check out this tutorial on Python String to Datetime.

## Quick Tips When Using timedelta

Let's look at a few things to keep in mind when using Python's `timedelta`:

1. It's best to use keyword arguments when calling `timedelta()` to avoid errors with units:

``interval = datetime.timedelta(weeks=1, days=3, hours=1, milliseconds=1354)``

2. When finding a time interval between two dates in different time zones, `timedelta` converts the dates to UTC dates before working out the time difference:

``````import zoneinfo

some_date = datetime.datetime.fromisoformat("2024-01-01T00:00:00")

some_date_lon = some_date.replace(tzinfo=zoneinfo.ZoneInfo("Europe/London"))
some_date_nyc = some_date.replace(tzinfo=zoneinfo.ZoneInfo("America/New_York"))

print(some_date_lon)
print(some_date_nyc)
print(some_date_nyc - some_date_lon)``````
``````2024-01-01 00:00:00+00:00
2024-01-01 00:00:00-05:00
5:00:00``````

The date in `some_date` shows the start of the new year. This is a naive `datetime` object since it doesn't have information about the time zone. However, `some_date_lon` and `some_date_nyc` are aware `datetime` objects since they represent the start of the new year in London and New York respectively.

The `timedelta` obtained by subtracting the two aware `datetime` objects shows a five-hour time interval, which is the UTC time difference.

3. Daylight saving changes are not taken into account by `timedelta`:

``````nyc = zoneinfo.ZoneInfo("America/New_York")

first_time = datetime.datetime.strptime("2024-03-10 1:00am", "%Y-%m-%d %I:%M%p")
first_time = first_time.replace(tzinfo=nyc)

second_time = datetime.datetime.strptime("2024-03-10 3:00am", "%Y-%m-%d %I:%M%p")
second_time = second_time.replace(tzinfo=nyc)

time_difference = second_time - first_time
print("Time difference between the first and second time:")
print(time_difference)

print("Checking the DST status of the first and second time:")
print(f"{first_time.dst() = }")
print(f"{second_time.dst() = }")``````
``````Time difference between the first and second time:
2:00:00

Checking the DST status of the first and second time:
first_time.dst() = datetime.timedelta(0)
second_time.dst() = datetime.timedelta(seconds=3600)``````

The two times represent 1:00 a.m. and 3:00 a.m. on March 3, 2024, in New York. Daylight saving started at 2:00 a.m. on the same day when the clocks moved to 3:00 a.m. The difference between the two times gives a `timedelta` that represents two hours even though only one hour passed between the two times because of the start of daylight saving.

We can convert to UTC if we need the real amount of time passed:

``````first_time_utc = first_time.astimezone(zoneinfo.ZoneInfo("UTC"))
second_time_utc = second_time.astimezone(zoneinfo.ZoneInfo("UTC"))
time_difference_utc = second_time_utc - first_time_utc

print("Actual time difference between the first and second time:")
print(time_difference_utc)``````
``````Actual time difference between the first and second time:
1:00:00``````

Converting to UTC before subtracting the `datetime` objects gives the actual time between the two `datetime` objects.

## Conclusion

Python's `timedelta` class offers straightforward methods for handling time intervals, making it easier to work with periods of time in various units. We've explored how to create `timedelta` objects and perform arithmetic operations with them, including addition, subtraction, multiplication, and division.

You can read more about dealing with dates and times in the following articles:

Author
Stephen Gruppetta

I studied Physics and Mathematics at UG level at the University of Malta. Then, I moved to London and got my PhD in Physics from Imperial College. I worked on novel optical techniques to image the human retina. Now, I focus on writing about Python, communicating about Python, and teaching Python.

Topics

Learn Python with these courses!

Course

### .css-1531qan{-webkit-text-decoration:none;text-decoration:none;color:inherit;}Introduction to Python

4 hr
5.6M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See Details
Start Course

Course

### Working with Dates and Times in Python

4 hr
57.9K
Learn how to work with dates and times in Python.

Course

### Manipulating Time Series Data in Python

4 hr
55.8K
In this course you'll learn the basics of working with time series data.
See More
Related

cheat sheet

### Working with Dates and Times in Python Cheat Sheet

Working with dates and times is essential when manipulating data in Python. Learn the basics of working with datetime data in this cheat sheet.

Richie Cotton

tutorial

### Python String to DateTime: How to Convert Strings to DateTime Objects in Python

In the tutorial, learn everything about the Python datetime module. Find a step-by-step guide for strings to datetime conversion, along with code samples and common errors.

Arunn Thevapalan

9 min

tutorial

### Python Datetime Tutorial

Learn how to create a datetime object.

DataCamp Team

2 min

tutorial

### Python time.sleep() Function

In this tutorial, you will learn how the time.sleep() function operates and how to apply it in your program.

Sejal Jaiswal

7 min

tutorial

### Python Range() Function Tutorial

Learn about the Python Range() function and its capabilities with the help of examples.