Menu Close

How to calculate the time interval between two time strings with Python?

Sometimes, we want to calculate the time interval between two time strings with Python.

In this article, we’ll look at how to calculate the time interval between two time strings with Python.

How to calculate the time interval between two time strings with Python?

To calculate the time interval between two time strings with Python, we can convert the time strings to datetimes with strptime and then take their difference.

For instance, we write

from datetime import datetime

s1 = '10:33:26'
s2 = '11:15:49' 
format = '%H:%M:%S'
tdelta = datetime.strptime(s2, format) - datetime.strptime(s1, format)

to call strptime with the time strings s2 and s1 and specify that they’re in the format format to convert the strings to datetime objects.

Then we subtract them to get a timedelta object with the difference between them.

Conclusion

To calculate the time interval between two time strings with Python, we can convert the time strings to datetimes with strptime and then take their difference.

Posted in Python, Python Answers