将日期列表拆分为连续日期的子集 [英] Split a list of dates into subsets of consecutive dates

查看:81
本文介绍了将日期列表拆分为连续日期的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组日期,其中可以包含多个日期范围。

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'
]

在此示例中,列表包含2个单独的连续日期范围(2020-01-01至2020-01-03和2020-01-06至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.

我正在寻找的其中一篇文章在(如何检测Python中的日期是否连续?)似乎是一种好方法,但是,我在用例中难以实现这一逻辑。

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.

推荐答案

更多itertools具有名为 consecutive_groups 会为您执行以下操作:

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)







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







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

这篇关于将日期列表拆分为连续日期的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆