请求开发日期校验函数:检测缺失月末日期与异常日期ID
实现
check_missing_or_wrong_balances函数 以下是满足需求的Python函数实现,包含详细逻辑说明:
函数代码
from datetime import date, timedelta def check_missing_or_wrong_balances(initial_date, balance_dates): today = date.today() missing_month_ends = [] invalid_ids = [] first_occurrence = {} # 工具函数:获取指定年月的月末日期 def get_month_end(year, month): # 通过下个月首日减一天得到当月最后一天,适配所有月份 if month == 12: next_month = date(year + 1, 1, 1) else: next_month = date(year, month + 1, 1) return next_month - timedelta(days=1) # 生成initial_date到today之间所有月份的月末日期集合 required_month_ends = set() current_year, current_month = initial_date.year, initial_date.month current_month_end = get_month_end(current_year, current_month) while current_month_end <= today: required_month_ends.add(current_month_end) # 切换到下一个月 if current_month == 12: current_year += 1 current_month = 1 else: current_month += 1 current_month_end = get_month_end(current_year, current_month) # 筛选缺失的月末日期,转为YYYY-mm-dd格式并排序 provided_dates = set(balance_dates.values()) missing_month_ends = sorted([d.strftime("%Y-%m-%d") for d in required_month_ends - provided_dates]) # 识别三类无效ID for id_num, dt in balance_dates.items(): # 1. 未来日期 if dt > today: invalid_ids.append(id_num) continue # 2. 非对应月份月末的日期 if dt != get_month_end(dt.year, dt.month): invalid_ids.append(id_num) continue # 3. 重复日期(仅保留首个出现的ID) if dt not in first_occurrence: first_occurrence[dt] = id_num else: invalid_ids.append(id_num) return (missing_month_ends, invalid_ids) # 测试示例 if __name__ == "__main__": initial_date = date(2021, 11, 30) balance_dates = { 1: date(2020, 5, 31), 2: date(2020, 6, 20), 3: date(2020, 6, 20), 4: date(2020, 8, 30), 5: date(2020, 5, 31), 6: date(2020, 12, 31), 7: date(2020, 5, 31), 8: date(2020, 11, 30), 9: date(2023, 2, 28), 10: date(2024, 5, 31), 11: date(2023, 11, 30), 12: date(2023, 2, 28) } missing_dates, invalid_ids = check_missing_or_wrong_balances(initial_date, balance_dates) print("缺失的月末日期:", missing_dates) print("无效ID列表:", invalid_ids)
逻辑说明
- 月末日期生成:用
get_month_end工具函数自动计算当月最后一天,无需手动处理2月、大月小月的差异。 - 缺失日期检查:生成目标时间段内所有必需的月末日期集合,与
balance_dates中的日期做差集,得到缺失项并格式化排序。 - 无效ID识别:
- 未来日期:直接对比日期是否晚于当日
- 非月末日期:计算该日期所在月份的月末,对比是否匹配
- 重复日期:用字典记录每个日期首次出现的ID,后续重复出现的ID直接归入无效列表
内容的提问来源于stack exchange,提问作者Pabluez
相关产品推荐
相关产品推荐

