Datetime Number Of Days Difference Group By Months
I want to find the days between two dates, but grouped by months. Example: start = datetime(2020,10,1) end = datetime(2020,12,15) end - start > datetime.timedelta(days=75) I
Solution 1:
Using itertools.groupby
to get number of days in each month:
import calendar
from datetime import datetime, timedelta
from itertools import groupby
start= datetime(2020,10,1)
end= datetime(2020,12,15)
for v, g in groupby(((start+ timedelta(days=i)).monthfor i inrange(1, (end-start).days +1))):
l =sum(1for _ in g)
print('{} {} in {}'.format(l, 'day' if l ==1else'days', calendar.month_name[v]))
Prints:
30 days in October
30 days in November
15 days in December
Post a Comment for "Datetime Number Of Days Difference Group By Months"