Group together arbitrary date objects that are within a time range of each other

前端 未结 3 1582
执笔经年
执笔经年 2020-12-15 14:31

I want to split the calendar into two-week intervals starting at 2008-May-5, or any arbitrary starting point.

So I start with several date objects:

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 14:57

    Use itertools groupby with lambda function to divide by the length of period the distance from starting point.

    >>> for i, group in groupby(range(30), lambda x: x // 7):
        print list(group)
    
    
    [0, 1, 2, 3, 4, 5, 6]
    [7, 8, 9, 10, 11, 12, 13]
    [14, 15, 16, 17, 18, 19, 20]
    [21, 22, 23, 24, 25, 26, 27]
    [28, 29]
    

    So with dates:

    import itertools as it
    start = DT.date(2008,5,5)
    lenperiod = 14
    
    for fnight,info in it.groupby(transactions,lambda data: (data[0]-start).days // lenperiod):
        print list(info)
    

    You can use also weeknumbers from strftime, and lenperiod in number of weeks:

    for fnight,info in it.groupby(transactions,lambda data: int (data[0].strftime('%W')) // lenperiod):
        print list(info)
    

提交回复
热议问题