Home > Backend Development > Python Tutorial > How to Calculate Time Intervals Between Strings in Python?

How to Calculate Time Intervals Between Strings in Python?

Mary-Kate Olsen
Release: 2024-11-15 01:56:02
Original
818 people have browsed it

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)
Copy after login

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
    )
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template