python计算当前时间的上个季度值

思路:首先定位出当前是时间属于第几季度;再使用减法实现计算(注意跨年的时候需要注意将年份同时减一);

代码如下:

# 定位季度    
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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值