如何统计两个日期区间内每个月份的出现次数
问题描述
给定闭区间内的两个日期:
start_date = '2018-06-01' end_date = '2022-10-01'
需要统计区间内各月份(不关联年份,仅统计1-12月每个自然月的出现次数),期望输出格式如下:
month | count ------------- 1 | 4 2 | 4 3 | 4 4 | 4 5 | 4 6 | 5 7 | 5 8 | 5 9 | 5 10 | 5 11 | 4 12 | 4
约束规则:
- 无预存的日期数据表,需直接通过起止日期计算
- 统计维度仅为月份,不需要关联对应年份
- 日期区间为闭区间,包含起止日期所属的月份
实现方法
不需要依赖第三方库,直接通过日期差值分段计算即可,逻辑如下:
- 将字符串格式的起止日期转换为日期对象
- 计算起止年份之间的完整年份数量,这部分每一个完整年都会给1-12月各贡献1次计数
- 累加起始日期所在年份,从起始月到当年12月的各月计数
- 累加结束日期所在年份,从当年1月到结束月的各月计数
- 按1-12月的顺序格式化输出结果
对应Python实现代码:
from datetime import datetime from collections import defaultdict start_date = '2018-06-01' end_date = '2022-10-01' start = datetime.strptime(start_date, '%Y-%m-%d') end = datetime.strptime(end_date, '%Y-%m-%d') month_count = defaultdict(int) # 累加中间完整年份的计数 full_year_count = end.year - start.year - 1 if full_year_count > 0: for month in range(1, 13): month_count[month] += full_year_count # 累加起始年的月份计数 for month in range(start.month, 13): month_count[month] += 1 # 累加结束年的月份计数 for month in range(1, end.month + 1): month_count[month] += 1 # 按指定格式输出 print("month | count") print("-------------") for month in range(1, 13): print(f"{month:<5} | {month_count[month]}")
运行上述代码即可得到和示例完全一致的输出结果,该方法时间复杂度固定为O(1),不需要遍历区间内的所有日期,计算效率极高。
内容的提问来源于stack exchange,提问作者Vinit Khandelwal
相关产品推荐
相关产品推荐

