Finding time interval between two times in Python

Finding time interval between two times in Python

Python language will not support arithmetic operation between datetime.time objects. If you try to perform such an arithmetic operation to find time interval between two time objects, you will get this error.

TypeError: unsupported operand type(s) for -: ‘datetime.time’ and ‘datetime.time’

The workaround is to install and use some additional package. Or, you can use the datetime object with some dummy date. Here, with an example, I will show how to use the datetime object to find the time interval between two times. In the example below, while initializing both the datetime objects, I have set the year, month and day to 1. This will crate a date “0001-01-01”. This will act as a dummy date and the subtraction of the datetime objects results a timedelta object which has the time interval.

## Time interval between two times
from datetime import datetime

# time objects
time_1 = datetime(year=1, month=1, day=1, hour=11, minute=50, second=45)
time_2 = datetime(year=1, month=1, day=1, hour=6, minute=23, second=12)

# difference between times
time_delta = time_1 - time_2        # time difference in timedelta data type

print("\nDate difference: ", time_delta, "\n")
Finding time interval between two times in Python

Related Article


Related Articles & Tools

Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.