Python time interval algorithm sum

Suppose 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 that the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a general function that also deals with all cases, such as one interval inside the other (so the result is an interval of a larger one), without intersection (so the result is the sum of both intervals).

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

thanks

+3
source share
4 answers
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
+3

, datetime .

, . , min max .

0

, , :

def interval(i1, i2):
    minstart, minend = [min(*e) for e in zip(i1, i2)]
    maxstart, maxend = [max(*e) for e in zip(i1, i2)]

    if minend < maxstart: # no overlap
        return minend-minstart + maxend-maxstart
    else: # overlap
        return maxend-minstart
0

datetime. datetime.datetime.strptime.

datetime.datetime, :

int1 = (start1, end1)
int2 = (start2, end2)

:

if end1 < start2 or end2 < start1:
    # The intervals are disjoint.
    return (end1-start1) + (end2-start2)
else:
    return max(end1, end2) - min(start1, start2)
0

Source: https://habr.com/ru/post/1715935/


All Articles