I have a list of dates, for example:
JavaScript
x
2
1
['2011-02-27', '2011-02-28', '2011-03-01', '2011-04-12', '2011-04-13', '2011-06-08']
2
How do I find the contiguous date ranges contained within those dates? In the above example, the ranges should be:
JavaScript
1
5
1
[{"start_date": '2011-02-27', "end_date": '2011-03-01'},
2
{"start_date": '2011-04-12', "end_date": '2011-04-13'},
3
{"start_date": '2011-06-08', "end_date": '2011-06-08'}
4
]
5
Thanks.
Advertisement
Answer
This works, but I’m not happy with it, will work on a cleaner solution an edit the answer. Done, here is a clean, working solution:
JavaScript
1
33
33
1
import datetime
2
import pprint
3
4
def parse(date):
5
return datetime.date(*[int(i) for i in date.split('-')])
6
7
def get_ranges(dates):
8
while dates:
9
end = 1
10
try:
11
while dates[end] - dates[end - 1] == datetime.timedelta(days=1):
12
end += 1
13
except IndexError:
14
pass
15
16
yield {
17
'start-date': dates[0],
18
'end-date': dates[end-1]
19
}
20
dates = dates[end:]
21
22
dates = [
23
'2011-02-27', '2011-02-28', '2011-03-01',
24
'2011-04-12', '2011-04-13',
25
'2011-06-08'
26
]
27
28
# Parse each date and convert it to a date object. Also ensure the dates
29
# are sorted, you can remove 'sorted' if you don't need it
30
dates = sorted([parse(d) for d in dates])
31
32
pprint.pprint(list(get_ranges(dates)))
33
And the relative output:
JavaScript
1
7
1
[{'end-date': datetime.date(2011, 3, 1),
2
'start-date': datetime.date(2011, 2, 27)},
3
{'end-date': datetime.date(2011, 4, 13),
4
'start-date': datetime.date(2011, 4, 12)},
5
{'end-date': datetime.date(2011, 6, 8),
6
'start-date': datetime.date(2011, 6, 8)}]
7