python date interval intersection
python date interval intersection
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Track title: CC I Beethoven Sonata No 31 in A Flat M
--
Chapters
00:00 Question
01:23 Accepted answer (Score 29)
01:51 Answer 2 (Score 17)
02:29 Answer 3 (Score 7)
03:00 Answer 4 (Score 4)
03:39 Thank you
--
Full question
https://stackoverflow.com/questions/3721...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datetime #intersection
#avk47
ACCEPTED ANSWER
Score 30
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.
ANSWER 2
Score 21
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.
ANSWER 3
Score 7
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
ANSWER 4
Score 3
Final Comparison: start <= other_finish and other_start <= finish
# All of the conditions below result in overlap I have left out the non overlaps
start <= other_start | start <= other_finish | other_start <= finish | finish <= other_finish
0 1 1 0
0 1 1 1
1 1 1 0
1 1 1 1
Only the start <= other_finish and other_start <= finish need to be true to return an overlap.