Sometimes, we want to find the time difference between two datetime objects in Python.
In this article, we’ll look at how to find the time difference between two datetime objects in Python.
How to find the time difference between two datetime objects in Python?
To find the time difference between two datetime objects in Python, we can subtract 2 datetime objects directly.
For instance, we write;
import datetime
first_time = datetime.datetime(2021, 1, 1)
later_time = datetime.datetime(2021, 1, 5)
diff = later_time - first_time
print(diff)
We create a datetime objects with the datetime.datetime
method.
Then we subtract later_time
from first_time
and assign that to diff
.
Then from the print
output, we see that diff
is 4 days, 0:00:00
.
Conclusion
To find the time difference between two datetime objects in Python, we can subtract 2 datetime objects directly.