使用/ python 将日期分成可管理的组

Chunking dates into mangeable groups w/ python

我需要在 30 天的块中创建日期块并遍历这些日期。例如,假设我想查看过去 3 年的 30 天增量。我需要以下内容:

第 1 块: end_date:2015 年 2 月 19 日 start_date:2015 年 1 月 20 日

第 2 块: end_date:2015 年 1 月 20 日 start_date: 12-21-2014

第 3 块: 块 4: ....

然后我将 start_date 和 end_date 插入 REST API 界面。

我正在尝试做这样的事情,然后使用 itertools groupby 提取最后 30 天。如有任何建议,我们将不胜感激。

chunk = now.strftime("%Y-%m-%d")
numdays = 1095
dateList = []
for x in range (0, numdays):
    dateList.append(chunk - datetime.timedelta(days = x))
print dateList

鉴于 dateutil 的解决方案,问题变成了如何轻松地从每个块中提取第一个和最后一个元素。我试图只遍历块并拉出 0/-1 元素,但这似乎是从每个块中拉出所有 30 个数据点。

 for start in chunks:
  print [chunks[0], chunks[-1]]

如果我手动将块[0] 分配给新元素,我可以打印它们。但这引出了一个问题,对所有块执行此操作的更有效方法是什么

chunk0 = chunks[0]
print [chunk0[0], chunk0[-1]]

我推荐使用 dateutil:

foo = list(
    dateutil.rrule.rrule(dateutil.rrule.DAILY, 
                         dtstart=datetime.date(2012, 2, 19),
                         until=datetime.date(2015, 2, 19))
)

然后:

In [36]: chunks = [foo[i:i+30] for i in range(0, len(foo), 30)]

In [37]: chunks[0]
Out[37]: 
[datetime.datetime(2012, 2, 19, 0, 0),
 datetime.datetime(2012, 2, 20, 0, 0),
 datetime.datetime(2012, 2, 21, 0, 0),
 datetime.datetime(2012, 2, 22, 0, 0),
 datetime.datetime(2012, 2, 23, 0, 0),
 datetime.datetime(2012, 2, 24, 0, 0),
 datetime.datetime(2012, 2, 25, 0, 0),
 datetime.datetime(2012, 2, 26, 0, 0),
 datetime.datetime(2012, 2, 27, 0, 0),
 datetime.datetime(2012, 2, 28, 0, 0),
 datetime.datetime(2012, 2, 29, 0, 0),
 datetime.datetime(2012, 3, 1, 0, 0),
 datetime.datetime(2012, 3, 2, 0, 0),
 datetime.datetime(2012, 3, 3, 0, 0),
 datetime.datetime(2012, 3, 4, 0, 0),
 datetime.datetime(2012, 3, 5, 0, 0),
 datetime.datetime(2012, 3, 6, 0, 0),
 datetime.datetime(2012, 3, 7, 0, 0),
 datetime.datetime(2012, 3, 8, 0, 0),
 datetime.datetime(2012, 3, 9, 0, 0),
 datetime.datetime(2012, 3, 10, 0, 0),
 datetime.datetime(2012, 3, 11, 0, 0),
 datetime.datetime(2012, 3, 12, 0, 0),
 datetime.datetime(2012, 3, 13, 0, 0),
 datetime.datetime(2012, 3, 14, 0, 0),
 datetime.datetime(2012, 3, 15, 0, 0),
 datetime.datetime(2012, 3, 16, 0, 0),
 datetime.datetime(2012, 3, 17, 0, 0),
 datetime.datetime(2012, 3, 18, 0, 0),
 datetime.datetime(2012, 3, 19, 0, 0)]

In [38]: chunks[-1]
Out[38]: 
[datetime.datetime(2015, 2, 3, 0, 0),
 datetime.datetime(2015, 2, 4, 0, 0),
 datetime.datetime(2015, 2, 5, 0, 0),
 datetime.datetime(2015, 2, 6, 0, 0),
 datetime.datetime(2015, 2, 7, 0, 0),
 datetime.datetime(2015, 2, 8, 0, 0),
 datetime.datetime(2015, 2, 9, 0, 0),
 datetime.datetime(2015, 2, 10, 0, 0),
 datetime.datetime(2015, 2, 11, 0, 0),
 datetime.datetime(2015, 2, 12, 0, 0),
 datetime.datetime(2015, 2, 13, 0, 0),
 datetime.datetime(2015, 2, 14, 0, 0),
 datetime.datetime(2015, 2, 15, 0, 0),
 datetime.datetime(2015, 2, 16, 0, 0),
 datetime.datetime(2015, 2, 17, 0, 0),
 datetime.datetime(2015, 2, 18, 0, 0),
 datetime.datetime(2015, 2, 19, 0, 0)]