gpt4 book ai didi

python时间间隔算法求和

转载 作者:太空狗 更新时间:2023-10-30 01:17:43 29 4
gpt4 key购买 nike

假设我有 2 个时间间隔,例如 16:30 - 20:00 和 15:00 - 19:00,我需要找到这两个时间间隔之间的总时间,所以结果是 5 小时(我将两个时间间隔相加并减去相交区间),我如何编写一个通用函数来处理所有情况,例如一个区间在另一个区间内(因此结果是较大区间的区间),没有交集(因此结果是两者的总和间隔)。

我的传入数据结构是原始的,只是像“15:30”这样的字符串,因此可能需要进行转换。

谢谢

最佳答案

from datetime import datetime, timedelta

START, END = xrange(2)
def tparse(timestring):
return datetime.strptime(timestring, '%H:%M')

def sum_intervals(intervals):
times = []
for interval in intervals:
times.append((tparse(interval[START]), START))
times.append((tparse(interval[END]), END))
times.sort()

started = 0
result = timedelta()
for t, type in times:
if type == START:
if not started:
start_time = t
started += 1
elif type == END:
started -= 1
if not started:
result += (t - start_time)
return result

从问题中测试你的时间:

intervals = [
('16:30', '20:00'),
('15:00', '19:00'),
]
print sum_intervals(intervals)

打印:

5:00:00

用不重叠的数据一起测试

intervals = [
('16:30', '20:00'),
('15:00', '19:00'),
('03:00', '04:00'),
('06:00', '08:00'),
('07:30', '11:00'),
]
print sum_intervals(intervals)

结果:

11:00:00

关于python时间间隔算法求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1324748/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com