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

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

    if quarter == 'last':
        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)
    elif 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)
    else:
        quarter_start = datetime.date(year, 10, 1)
        _, days = calendar.monthrange(year, 12)
        quarter_end = datetime.date(year, 12, days)
    return quarter_start, quarter_end
posted @ 2022-12-14 13:52  cnblogs用户  阅读(671)  评论(0编辑  收藏  举报