0

I have a list of dates which are mostly consecutive, for example:

['01-Jan-10', '02-Jan-10', '03-Jan-10', '04-Jan-10', '08-Jan-10', '09-Jan-10', '10-Jan-10', '11-Jan-10', '13-Jan-10']

This is just an illustration as the full list contains thousands of dates.

This list can have couple of spots where the consecutiveness breaks. In the example shown above, it is 05-Jan-10, 07-Jan-10, and then 12-Jan-10. I am looking for the minimal and maximal day in the gap time span. Is there any way to do this efficiently in python?

jarmod
  • 71,565
  • 16
  • 115
  • 122
Sam333
  • 199
  • 14

1 Answers1

1

The datetime package from the standard library can be useful.

Check the right date format and apply it with strptime to all terms in the list, loop through a pairs and check the difference between (in days) them using timedelta arithmetics. To keep the same format (which is non-standard) you need apply strftime.

from datetime import datetime, timedelta

dates = ['01-Jan-10', '02-Jan-10', '03-Jan-10', '04-Jan-10', '08-Jan-10', '09-Jan-10', '10-Jan-10', '11-Jan-10', '13-Jan-10']

# date format code
date_format = '%d-%b-%y'

# cast to datetime objects
days = list(map(lambda d: datetime.strptime(d, date_format).date(), dates))

# check consecutive days
for d1, d2 in zip(days, days[1:]):
    date_gap = (d2-d1).days
    # check consecutiveness
    if date_gap > 1:
        # compute day boundary of the gap
        min_day_gap, max_day_gap = d1 + timedelta(days=1), d2 - timedelta(days=1)

        # apply format
        min_day_gap = min_day_gap.strftime(date_format)
        max_day_gap = max_day_gap.strftime(date_format)

        # check
        print(min_day_gap, max_day_gap)

#05-Jan-10 07-Jan-10
#12-Jan-10 12-Jan-10

Remark: it is not clear what would happen when the time gap is of 2 days, in this case the min & max day in the gap are identical. In that case add a conditional check date_gap == 2 and correct the behavior...

if date_gap == 2: ... elif date_gap > 1: ...

or add a comment/edit the question with a proper description.

cards
  • 3,936
  • 1
  • 7
  • 25