Search code examples
pythonpython-3.xdatetimepython-dateutilrrule

Using rrule to assign days to relevant months


I was able to list the days between two dates using rrule like so:

from dateutil import rrule
from datetime import datetime

a = '20180306'
b = '20180506'

for dt in rrule.rrule(rrule.DAILY,
                  dtstart = datetime.strptime(a, '%Y%m%d'),
                  until = datetime.strptime(b, '%Y%m%d')):
    print (dt.strftime('%Y%m%d'))

the output given is:

20180306
20180307
...
20180408
20180409
...
20180506

How can I go about assigning these days to their relevant months to give an output of:

March-18: 26 days
April-18: 30 days
May-18: 6 days

I am also curious about how to extend this to include hours in the calculation ie.

March-18: 11.9 days

Thanks black.mamba


Solution

  • You can use itertools.groupby and extract the length of each group. In the below example, both grouper and res are lazy iterators, so you can extract results by iteration.

    from dateutil import rrule
    from datetime import datetime
    from itertools import groupby
    
    a = '20180306'
    b = '20180506'
    
    rule = rrule.rrule(rrule.DAILY,
                       dtstart=datetime.strptime(a, '%Y%m%d'),
                       until=datetime.strptime(b, '%Y%m%d'))
    
    grouper = groupby(rule, key=lambda x: x.strftime('%B-%y'))
    
    res = ((i, len(list(j))) for i, j in grouper)
    
    for month, count in res:
        print('{0}: {1} days'.format(month, count))
    
    March-18: 26 days
    April-18: 30 days
    May-18: 6 days