python date interval intersection

It's not really more Pythonic, but you can simply the logic to decide on an intersection somewhat. This particular problems crops up a lot:

return (t1start <= t2start <= t1end) or (t2start <= t1start <= t2end)

To see why this works think about the different possible ways that the two intervals can intersect and see that the starting point of one must always be within the range of the other.


An alternative and hopefully more intelligible solution:

def has_overlap(A_start, A_end, B_start, B_end):
    latest_start = max(A_start, B_start)
    earliest_end = min(A_end, B_end)
    return latest_start <= earliest_end:

We can get the interval of the overlap easily, it is (latest_start, earliest_end). Note that latest_start can be equal to earliest_end.

It should be noted that this assumes that A_start <= A_end and B_start <= B_end.


Here's a version that give you the range of intersection. IMHO, it might not be the most optimize # of conditions, but it clearly shows when t2 overlaps with t1. You can modify based on other answers if you just want the true/false.

if (t1start <= t2start <= t2end <= t1end):
    return t2start,t2end
elif (t1start <= t2start <= t1end):
    return t2start,t1end
elif (t1start <= t2end <= t1end):
    return t1start,t2end
elif (t2start <= t1start <= t1end <= t2end):
    return t1start,t1end
else:
    return None