思路:首先定位出当前是时间属于第几季度;再使用减法实现计算(注意跨年的时候需要注意将年份同时减一);
代码如下:
# 定位季度
def location_quarter(time):
"""
:param time: yyyy-MM-dd格式的时间字符串
:return: 定位当前时间所在的季度值,格式:2022CQ3
"""
year = time[0:4]
month = time[5:7]
current_quarter = None
if month in ("01", "02", "03"):
current_quarter = year + "CQ1"
elif month in ("04", "05", "06"):
current_quarter = year + "CQ2"
elif month in ("07", "08", "09"):
current_quarter = year + "CQ3"
else:
current_quarter = year + "CQ4"
return current_quarter
# 计算上个季度
def get_last_quarter(time):
"""
:param time: yyyy-MM-dd格式的字符串时间
:return: 返回当前时间的上个季度的值,格式:2022CQ3
"""
year = int(time[0:4])
month = int(time[5:7])
quarter = int(location_quarter(time)[6:7])
if quarter == 1:
year = year - 1
quarter = 4
return str(year) + "CQ" + str(quarter)
else:
return str(year) + "CQ" + str(quarter - 1)