如何在Python中計算字串之間的時間間隔?

Mary-Kate Olsen
發布: 2024-11-15 01:56:02
原創
760 人瀏覽過

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 < 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.

以上是如何在Python中計算字串之間的時間間隔?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板