Python如何获取从指定年份到当前日期的季度周期列表?
季度周期列表生成代码修正方案
现有代码问题
- 仅遍历了起始年到当前年份的前一年,未包含当前年份已结束的季度
- 没有计算当前时间对应的上一季度编号,无法匹配需求中仅输出到上一季度的要求
修正后代码
import datetime import json from_year = 2018 now = datetime.datetime.now() current_year = now.year # 计算当前所处季度 current_quarter = (now.month - 1) // 3 + 1 # 推导上一季度的所属年份和季度编号 if current_quarter > 1: last_quarter_year = current_year last_quarter = current_quarter - 1 else: # 若当前为第一季度,上一季度为去年第四季度 last_quarter_year = current_year - 1 last_quarter = 4 period = [] # 追加所有完整自然年的四个季度 for year in range(from_year, last_quarter_year): period += [f"{year}K{i}" for i in range(1,5)] # 追加最后一个年份到上一季度为止的所有季度 period += [f"{last_quarter_year}K{i}" for i in range(1, last_quarter + 1)] quarter = json.dumps(period) print(quarter)
效果说明
如果当前时间为2021年第二季度(即4-6月),运行代码后输出结果和你给出的期望输出完全一致:["2018K1", "2018K2", "2018K3", "2018K4", "2019K1", "2019K2", "2019K3", "2019K4", "2020K1", "2020K2", "2020K3", "2020K4","2021K1"]
代码同时兼容边界场景:如果当前为2024年1月(第一季度),上一季度为2023年第四季度,代码会自动输出到2023K4为止的所有季度,不会包含未结束的2024年季度。
内容的提问来源于stack exchange,提问作者AXz
相关产品推荐
相关产品推荐

