Datetime按月、年分组的天数差异



我要查找两个日期之间的天数,但按月和年分组。

按月参照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

相关内容

  • 没有找到相关文章

最新更新