Bootstrap

获取当前月的第一天和最后一天,上一个月的第一天和最后一天

运用到的点,觉得写的还行,就分享一下

import datetime
import calendar


def get_date():
    """
    获取上月第一天和最后一天并返回 (元组)
    example:
    now date:2020-10-12
    return:2020-09-01,2020-09-30
    """
    today = datetime.date.today()  # 当前日期

    last_day_last_month = datetime.date(today.year, today.month, 1) - datetime.timedelta(1)  # 上个月最后一天
    first_day_last_month = datetime.date(last_day_last_month.year, last_day_last_month.month, 1)  # 上个月第一天

    first_day_month = datetime.date(today.year, today.month, 1)  # 这个月第一天
    days_nums = calendar.monthrange(today.year, today.month)[1]  # 获取一个月有多少天

    last_day_month = first_day_month + datetime.timedelta(days=days_nums - 1)  # 这个月最后一天

    print("上个月第一天:{}\n上个月最后一天:{}\n这个月第一天:{}\n这个月最后一天:{}\n"
          .format(first_day_last_month, last_day_last_month, first_day_month, last_day_month))

    return first_day_last_month, last_day_last_month

运行结果如下
在这里插入图片描述

;