Home >Backend Development >Python Tutorial >How do I calculate time intervals and average durations between time strings in Python?
Calculating Time Intervals Between Time Strings
Determining the time difference between two time strings in Python can be a straightforward task with the help of the datetime module. Let's explore how to achieve this and address the additional need for calculating averages.
To parse the time strings into datetime objects, we can utilize the datetime.strptime() method. Consider the following example:
from datetime import datetime start_time = "10:33:26" end_time = "11:15:49" FMT = '%H:%M:%S' # Parse time strings into datetime objects start_dt = datetime.strptime(start_time, FMT) end_dt = datetime.strptime(end_time, FMT)
The result is two datetime objects, start_dt and end_dt, which represent the start and end times.
Calculating Time Interval
To calculate the time interval between the two times, subtract the start_dt from the end_dt:
time_interval = end_dt - start_dt
time_interval will be a timedelta object that contains the difference between the two times. You can access the duration values in hours, minutes, and seconds using the hours, minutes, and seconds attributes, respectively.
Calculating Average Duration
To calculate the average duration from multiple time intervals, you can convert them to seconds and then take the average:
# Convert the time interval to seconds interval_seconds = time_interval.total_seconds() # Store the converted seconds in a list seconds_list.append(interval_seconds) # Calculate the average duration average_seconds = sum(seconds_list) / len(seconds_list)
Handling Negative Results
If the end time occurs before the start time, the time_interval will be negative. To handle this case, you can manually set the days to zero, assuming the interval crosses midnight:
if time_interval.days < 0: time_interval = timedelta( days=0, seconds=time_interval.seconds, microseconds=time_interval.microseconds )
The above is the detailed content of How do I calculate time intervals and average durations between time strings in Python?. For more information, please follow other related articles on the PHP Chinese website!