我正在尝试获取从给定期间到当前日期的季度期间。我想要的是本年度的上一个季度,例如2021K4,而不是本季度。以下是我用来获取它的代码。
import datetime
import json
from_year = 2018
last_year = datetime.datetime.now().year
year_list = list(range(from_year, last_year))
period = []
for all_year in year_list:
all_months = [str(all_year)+'K'+str(i) for i in list(range(1,5))]
period = period + all_months
quarter = json.dumps(period)
print(quarter)
输出-["2018K1","2018K2","2018 K3","201K4","2019K1","2019K2","2019 K3","2020K1","202 K2","2020 K3","2021 K4"]
期望输出-["2018K1","2018K2","2018 K3","201K4","2019K1","2019K2","2019 K3","2020K1","2020 K2","2021K1〃]
问题是在定义year_list 时
尝试这样做:
import datetime
import json
from_year = 2018
current_year = datetime.datetime.now().year
current_month = int(datetime.datetime.now().strftime("%m"))
year_list = list(range(from_year, current_year+1))
period = []
for all_year in year_list:
if all_year != current_year:
all_months = [str(all_year)+'K'+str(i) for i in list(range(1,5))]
period += all_months
else:
for q in range (1,((current_month-1)//3+1)):
period.append(str(current_year)+'K'+str(q))
quarter = json.dumps(period)
print(quarter)