如何計算 HH:MM:SS 格式的兩個字串之間的時間間隔?

Barbara Streisand
發布: 2024-11-15 07:13:02
原創
630 人瀏覽過

How to Calculate the Time Interval Between Two Strings in HH:MM:SS Format?

Calculating the Time Interval Between Two Strings

Determining the time difference between two strings in HH:MM:SS format can be a useful task for various applications. Using Python's datetime and time modules, this computation can be efficiently performed.

To parse the strings into datetime objects, employ the datetime.strptime() method. Then, calculate the time difference using the subtraction operator (-) between the parsed datetime objects. This yields a timedelta object containing the difference.

from datetime import datetime

s1 = '10:33:26'
s2 = '11:15:49'
FMT = '%H:%M:%S'

tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
登入後複製

To convert the timedelta to seconds for averaging, utilize the total_seconds() method. Then, compute the average by summing the seconds and dividing by the number of intervals.

total_seconds = tdelta.total_seconds()
avg_seconds = total_seconds / number_of_intervals
登入後複製

For scenarios where the end time precedes the start time, adjustments may be required to ensure the interval calculation assumes the crossing of midnight. Consider the following code snippet:

if tdelta.days < 0:
    tdelta = timedelta(
        days=0,
        seconds=tdelta.seconds,
        microseconds=tdelta.microseconds
    )
登入後複製

By employing this approach, you can effectively determine the time interval between two time strings and perform further computations like averaging.

以上是如何計算 HH:MM:SS 格式的兩個字串之間的時間間隔?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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