I have a list of date ranges and want to find the total number of days between those ranges. However, the ranges may, or may not, have overlap. And I want to exclude overlapped time. There may also be gaps between the ranges which I also want to exclude.
I’m curious on the most optimal way to calculate this.
An example:
JavaScript
x
6
1
ranges = [
2
{'start': 1/1/2001, 'end': 1/1/2002},
3
{'start': 1/1/2000, 'end': 1/1/2002},
4
{'start': 1/1/2003, 'end': 1/1/2004},
5
]
6
Total range time in days — 1/1/2000 through 1/1/2002 + 1/1/2003 through 1/1/2004
Advertisement
Answer
JavaScript
1
33
33
1
from datetime import datetime, timedelta
2
3
ranges = [
4
{'start': '1/1/2001', 'end': '1/1/2002'},
5
{'start': '1/1/2000', 'end': '1/1/2002'},
6
{'start': '1/1/2003', 'end': '1/1/2004'},
7
]
8
9
# Sort the list of date ranges by the start date
10
ranges = sorted(ranges, key=lambda x: datetime.strptime(x['start'], '%m/%d/%Y'))
11
12
# Initialize the start and end dates for the non-overlapping and non-gapped ranges
13
start_date = datetime.strptime(ranges[0]['start'], '%m/%d/%Y')
14
end_date = datetime.strptime(ranges[0]['end'], '%m/%d/%Y')
15
total_days = 0
16
17
# Iterate through the list of date ranges
18
for i in range(1, len(ranges)):
19
current_start_date = datetime.strptime(ranges[i]['start'], '%m/%d/%Y')
20
current_end_date = datetime.strptime(ranges[i]['end'], '%m/%d/%Y')
21
22
# Check for overlaps and gaps
23
if current_start_date <= end_date:
24
end_date = max(end_date, current_end_date)
25
else:
26
total_days += (end_date - start_date).days
27
start_date = current_start_date
28
end_date = current_end_date
29
30
# Add the last range to the total days
31
total_days += (end_date - start_date).days
32
print(total_days)
33