我要查找两个日期之间的天数,但按月和年分组。
按月参照Datetime天数差组
import calendar
from datetime import datetime, timedelta
from itertools import groupby
start = datetime(2020,12,30)
end = datetime(2021,12,15)
如果开始年份和结束年份不同,我需要按月和按年的结果组。我如何应用代码来得到答案?
Thank you so much
基于另一个答案中分享的想法,您创建一个日期列表,将它们map
到您想要的组,然后使用groupby
计数
from datetime import datetime, timedelta
from itertools import groupby
start = datetime(2020,12,30)
end = datetime(2021,12,15)
dates = (start + timedelta(days=i) for i in range(1, (end - start).days + 1))
year_months = map(lambda x: (x.year, x.month), dates)
for v, g in groupby(year_months):
print(v, sum(1 for _ in g))
Output:
(2020, 12) 1
(2021, 1) 31
(2021, 2) 28
(2021, 3) 31
(2021, 4) 30
(2021, 5) 31
(2021, 6) 30
(2021, 7) 31
(2021, 8) 31
(2021, 9) 30
(2021, 10) 31
(2021, 11) 30
(2021, 12) 15