ホームページ >バックエンド開発 >Python チュートリアル >HH:MM:SS 形式の 2 つの文字列間の時間間隔を計算するにはどうすればよいですか?
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 形式の 2 つの文字列間の時間間隔を計算するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。