关于获取日期的几种常见情况

1、获取距离当前日期前n个月的日期

def get_before_months_date(months):
    """
        获取距离当前日期前n个月的日期  eg:2022-06-17
        :param months: 间隔的月数
    """
    months_ago_date = (datetime.date.today() + relativedelta(months=-months)).strftime("%Y-%m-%d")
    return months_ago_date

2、获取指定月份的最后一天的日期

def get_month_last_date(year, month):
    """
        获取指定月份的最后一天的日期 eg: 2022-05-31
    """
    day = int(calendar.month(year, month)[-3:-1])
    month_last_date = datetime.datetime.strptime('%s-%s-%s' % (year, month, day),'%Y-%m-%d').strftime('%Y-%m-%d')
    return month_last_date

3、获取指定月份的下几月

def get_next_month(date=None, n=0):
    """
        获取指定月份的下几月  传入2022-02返回 2022-03
        n: 1~12
    """
    current_year = date[:4]
    current_month = int(date[5:7])
    # 1月的上个月是去年的12月
    if current_month + n > 12:
        next_year = str(int(current_year)+1)
        next_month = next_year + '-' + str(current_month+n-12).zfill(2)
    else:
        next_month = current_year + '-' + str(current_month + n).zfill(2)
    return next_month

你可能感兴趣的:(Python笔记,python)