views:

754

answers:

4

Hello 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

A: 

I'll assume you can do the conversion to something like datetime on your own.

Sum the two intervals, then subtract any overlap. You can get the overlap by comparing the min and max of each of the two ranges.

Mark Ransom
+2  A: 
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
nosklo
Doesn't work if there isn't an overlap.
Mark Ransom
@Mark: Fixed
nosklo
A: 

Code for when there is an overlap, please add it to one of your solutions:

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
tonfa
A: 

You'll want to convert your strings into datetimes. You can do this with datetime.datetime.strptime.

Given intervals of datetime.datetime objects, if the intervals are:

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

Then isn't it just:

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