Search code examples
pythondjangotimestamplogic

Python Django filter avoid overlapping between range dates


I'm having a bit of a logic blank this morning.

I get 2 datetime objects from a user (a range), start_time and end_time.

Idea is to return an exists if there's an overlap between the input range and an existing schedule time.

I tried the following, but I'm far off with the logic.

if Schedule.objects.filter(start_date__gte=ts_start, end_date__lte=ts_start).filter(start_date__gte=ts_end, end_date__lte=ts_end ).exists():

Solution

  • Two ranges [b1, e1] and [b2, be] do not overlap if b1>e2, or e1<b2. We can negate this expression to know when two intervals overlap: b1≤e2, and e1≥b2.

    This thus means that we can filter with:

    Schedule.objects.filter(start_date__lte=ts_end, end_date__gte=ts_start)