python间隔时间,python时间间隔算法总和

Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval inside other(so the result is the interval of the bigger one), no intersection (so the result is the sum of both intervals).

My incoming data structure is primitive, simply string like "15:30" so a conversion may be needed.

Thanks

解决方案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

Testing with your times from the question:

intervals = [

('16:30', '20:00'),

('15:00', '19:00'),

]

print sum_intervals(intervals)

That prints:

5:00:00

Testing it together with data that doesn't overlap

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)

result:

11:00:00

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值