"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Calculate Time Intervals Between Strings in Python?

How to Calculate Time Intervals Between Strings in Python?

Published on 2024-11-12
Browse:433

How to Calculate Time Intervals Between Strings in Python?

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 

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3