Get Time Difference Between Two Dates & Times in Python (datetime Module)

This post explains how to calculate time differences between two different datetimes in the Python programming language.

Example Data and datetime Module

We can import the datetime module as shown in the following Python code.

import datetime

The two datetime objects below will be used for the examples of this article.

The first date and time object:

dt_a = datetime.datetime(2026, 5, 10, 3, 45)
print(dt_a)
# 2026-05-10 03:45:00

The second date and time object:

dt_b = datetime.datetime(2028, 3, 18, 8, 11)
print(dt_b)
# 2028-03-18 08:11:00

Example: Subtract One datetime Object from Another

The Python code below subtracts the datetime object dt_b from the datetime object dt_a:

dt_difference = dt_a - dt_b
print(dt_difference)
# -679 days, 19:34:00

The result shows a negative number of days because the second date is at a later point in time than the first date.

 

Further Resources

Please find some related tutorials below.

 

Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Menu
Top