Calculating Time Intervals Between Strings in Python
To determine the time interval between two strings representing time in the format HH:MM:SS, you can leverage Python's datetime.strptime() method. This method effectively parses a string into an equivalent datetime object.
For instance, the following code snippet showcases its application:
from datetime import datetime s1 = '10:33:26' s2 = '11:15:49' # for example FMT = '%H:%M:%S' tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
As a result, you obtain a timedelta object encapsulating the time difference. This object offers versatility in manipulations, such as conversion to seconds or incorporation into datetime objects.
Note that if the end time precedes the start time (e.g., s1 = 12:00:00, s2 = 05:00:00), a negative value will be returned. To account for situations where the interval spans midnight, consider incorporating these lines after the previous code:
if tdelta.days < 0: tdelta = timedelta( days=0, seconds=tdelta.seconds, microseconds=tdelta.microseconds )
This adjustment ensures the code interprets the time interval as crossing midnight (assuming the end time is never earlier than the start time).
To calculate averages, converting the time intervals to seconds and then performing the calculation is a viable approach.
The above is the detailed content of How to Calculate Time Intervals Between Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!