• 欢迎光临~

python获取当前季度或上一季度的起止日期

开发技术 开发技术 2022-12-14 次浏览
import datetime
import calendar


def get_quarter_date(quarter='current'):
    """
    获取当前季度或上一季度的起止日期
    :param quarter: [current , last], default current
    :return: tuple of datetime.date
    """
    today = datetime.date.today()
    year = today.year
    current_quarter = ((today.month - 1) // 3) + 1
    quarter_start = quarter_end = None

    if quarter == 'current':
        if current_quarter == 4:
            quarter_start = datetime.date(year, 10, 1)
            _, days = calendar.monthrange(year, 12)
            quarter_end = datetime.date(year, 12, days)
    else:
        current_quarter -= 1
        if current_quarter == 0:
            quarter_start = datetime.date(year - 1, 10, 1)
            _, days = calendar.monthrange(year - 1, 12)
            quarter_end = datetime.date(year - 1, 12, days)
    if current_quarter == 1:
        quarter_start = datetime.date(year, 1, 1)
        _, days = calendar.monthrange(year, 3)
        quarter_end = datetime.date(year, 3, days)
    elif current_quarter == 2:
        quarter_start = datetime.date(year, 4, 1)
        _, days = calendar.monthrange(year, 6)
        quarter_end = datetime.date(year, 6, days)
    elif current_quarter == 3:
        quarter_start = datetime.date(year, 7, 1)
        _, days = calendar.monthrange(year, 9)
        quarter_end = datetime.date(year, 9, days)
    return quarter_start, quarter_end
程序员灯塔
转载请注明原文链接:python获取当前季度或上一季度的起止日期
喜欢 (0)