基于自定义业务月份与财年规则的Python序列生成需求
业务内部日历财年月序列生成实现(Python)
需求背景
某新业务线于2020年1月启动,业务内部日历规则如下:
- 2020年1月为第1个月,2月为第2个月……12月为第12个月,2021年1月为第13个月,以此类推
- 该业务财年起始月份为2月
示例说明
示例1
假设输入日期为2023年5月(对应业务内部日历第41个月),输出应为:
(41,40,39,38)
其中41为当前财年的当前月份,38为当前财年2月对应的业务月份编号。
示例2
输入日期为2023年1月(对应业务内部日历第37个月),输出应为:
(37,36,35,34,33,32,31,30,29,28,27,26)
其中37为当前月份,26为上一财年2月对应的业务月份编号。
Python实现代码
from datetime import datetime def get_fy_month_sequence(input_date: datetime) -> tuple: # 计算业务内部月份编号:2020年1月为第1个月 base_year = 2020 base_month = 1 months_since_start = (input_date.year - base_year) * 12 + (input_date.month - base_month) + 1 # 确定当前财年的起始业务月份 fy_start_month = 2 # 财年起始为2月 if input_date.month >= fy_start_month: # 当前月份在财年内,财年起始业务月份为当年2月对应的编号 fy_start_biz_month = (input_date.year - base_year) * 12 + (fy_start_month - base_month) + 1 else: # 当前月份在上一财年,财年起始业务月份为上一年2月对应的编号 fy_start_biz_month = (input_date.year - 1 - base_year) * 12 + (fy_start_month - base_month) + 1 # 生成从当前业务月份倒序到财年起始月份的序列 month_sequence = tuple(range(months_since_start, fy_start_biz_month - 1, -1)) return month_sequence # 测试示例1 date1 = datetime(2023, 5, 1) print(get_fy_month_sequence(date1)) # 输出: (41, 40, 39, 38) # 测试示例2 date2 = datetime(2023, 1, 1) print(get_fy_month_sequence(date2)) # 输出: (37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26)
代码逻辑说明
- 计算业务内部月份编号:以2020年1月为基准,通过年份差和月份差的计算,得到当前日期对应的业务月份数。
- 确定财年起始业务月份:
- 若当前月份≥2月,财年起始为当年2月对应的业务月份编号
- 若当前月份<2月,财年起始为上一年2月对应的业务月份编号
- 生成序列:从当前业务月份开始,倒序生成到财年起始月份的所有编号,最终转为元组返回。
内容的提问来源于stack exchange,提问作者MaDMaXx
相关产品推荐
相关产品推荐

