[Answered ]-How to query overlapping dates on Postgres DateRange field

1👍

We know that two datetimes do not overlap if e1≤s2 or e2≤s1 with si and ei the start and end of fragment i respectively.

This thus means that the two do overlap in case e1>s2 and e2>s1. We thus can construct an overlap check with:

def is_overlap(dr1, dr2):
    return dr1.upper > dr2.lower and dr2.upper > dr1.lower

Next we can find out if any of the items overlaps with:

any(is_overlap(query_date, dr) for dr in mylist)

or we can construct a list of all DateRanges that overlap with query_date:

[dr for dr in mylist if is_overlap(query_date, dr)]

Leave a comment