Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list of dates into subsets of consecutive dates

I've got an array of dates that can contain multiple date ranges in it.

dates = [
 '2020-01-01',
 '2020-01-02',
 '2020-01-03',
 '2020-01-06',
 '2020-01-07',
 '2020-01-08'
]

In this example, the list contains 2 separate consecutive date ranges (2020-01-01 to 2020-01-03 & 2020-01-06 to 2020-01-08)

I'm attempting to figure out how I would loop through this list and find all the consecutive date ranges.

One of the articles I'm looking at (How to detect if dates are consecutive in Python?) seems to have a good approach, however, I'm struggling to implement this logic in my use case.

like image 720
pyFiddler Avatar asked Jan 16 '20 17:01

pyFiddler


1 Answers

More itertools has a function called consecutive_groups that does this for you:

Or you can view the source code and copy it's approach:

from datetime import datetime
from itertools import groupby
from operator import itemgetter

def consecutive_groups(iterable, ordering=lambda x: x):
    for k, g in groupby(enumerate(iterable), key=lambda x: x[0] - ordering(x[1])):
        yield map(itemgetter(1), g)

Then to use the function:

for g in consecutive_groups(dates, lambda x: datetime.strptime(x, '%Y-%m-%d').toordinal()):
    print(list(g))

Or (more appropriately) using a function instead of lambda:

def to_date(date):
    return datetime.strptime(date, '%Y-%m-%d').toordinal()

for g in consecutive_groups(dates, to_date):
    print(list(g))

['2020-01-01', '2020-01-02', '2020-01-03']
['2020-01-06', '2020-01-07', '2020-01-08']
like image 71
Jab Avatar answered Oct 16 '22 13:10

Jab