python时间间隔算法总和 [英] python time interval algorithm sum

查看:179
本文介绍了python时间间隔算法总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

谢谢

推荐答案

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)

打印:

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)

结果:

11:00:00

这篇关于python时间间隔算法总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆