Skip to content

Instantly share code, notes, and snippets.

@ervinne13
Created September 21, 2022 02:24
Show Gist options
  • Save ervinne13/59a99ed217617d23dfe54544b353a21f to your computer and use it in GitHub Desktop.
Save ervinne13/59a99ed217617d23dfe54544b353a21f to your computer and use it in GitHub Desktop.
Get # of days that overlap between two ranges. Usually use this to check if a date range falls within another, larger date range but might as well check for any overlap.
from datetime import datetime
from collections import namedtuple
Range = namedtuple('Range', ['start', 'end'])
# Returns a positive number of days overlapping, otherwise, returns 0
def get_days_overlap(r1: Range, r2: Range) -> int:
latest_start = max(r1.start, r2.start)
earliest_end = min(r1.end, r2.end)
delta = (earliest_end - latest_start).days + 1
overlap = max(0, delta)
return overlap
if __name__ == '__main__':
def __assert_no_overlaps_for_months_apart():
assert 0 == get_days_overlap(
Range(start=datetime(2022, 9, 1), end=datetime(2022, 9, 30)),
Range(start=datetime(2022, 12, 1), end=datetime(2022, 12, 31))
)
def __assert_no_overlaps_for_adjacent_months():
assert 0 == get_days_overlap(
Range(start=datetime(2022, 9, 1), end=datetime(2022, 9, 30)),
Range(start=datetime(2022, 10, 1), end=datetime(2022, 10, 31))
)
def __assert_same_range_overlaps():
assert 30 == get_days_overlap(
Range(start=datetime(2022, 9, 1), end=datetime(2022, 9, 30)),
Range(start=datetime(2022, 9, 1), end=datetime(2022, 9, 30))
)
def __assert_days_overlap_a_day():
assert 1 == get_days_overlap(
Range(start=datetime(2022, 9, 1), end=datetime(2022, 9, 30)),
Range(start=datetime(2022, 9, 30), end=datetime(2022, 10, 5))
)
def __assert_days_overlap_for_range_within_range():
assert 7 == get_days_overlap(
Range(start=datetime(2022, 9, 1), end=datetime(2022, 9, 30)),
Range(start=datetime(2022, 9, 11), end=datetime(2022, 9, 17))
)
__assert_no_overlaps_for_months_apart()
__assert_no_overlaps_for_adjacent_months()
__assert_same_range_overlaps()
__assert_days_overlap_a_day()
__assert_days_overlap_for_range_within_range()
print('Works fine')
@ervinne13
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment