Python 获取本周、上周、下周周一、周天的日期

1、获取本周(指定日期)周一、周天的日期
# date: "2022-08-09"
def get_current_week(date=None):
    if date:
        duty_date = datetime.datetime.strptime(str(date), '%Y-%m-%d')
        monday, sunday = duty_date, duty_date
    else:
        monday, sunday = datetime.date.today(), datetime.date.today()
    one_day = datetime.timedelta(days=1)
    while monday.weekday() != 0:
        monday -= one_day
    while sunday.weekday() != 6:
        sunday += one_day

    # return monday, sunday
    # 返回时间字符串
    return datetime.datetime.strftime(monday, "%Y-%m-%d"), datetime.datetime.strftime(sunday, "%Y-%m-%d")
2、获取上周周一、周天的日期
# date: "2022-08-09"
def get_last_week(date=None):
    if date:
        today = datetime.datetime.strptime(str(date), '%Y-%m-%d')
    else:
        today = datetime.datetime.today()
    end_time = today - datetime.timedelta(days=today.isoweekday())
    start_time = end_time - datetime.timedelta(days=6)
    return start_time.strftime("%Y-%m-%d"), end_time.strftime("%Y-%m-%d")
3、获取下周周一、周天的日期
# date: "2022-08-09"
def get_next_week(date=None):
    if date:
        today = datetime.datetime.strptime(str(date), '%Y-%m-%d')
    else:
        today = datetime.datetime.today()
    start_time = today + datetime.timedelta(days=7-today.weekday())
    end_time = start_time + datetime.timedelta(days=6)
    return start_time.strftime("%Y-%m-%d"), end_time.strftime("%Y-%m-%d")
    
4、根据开始日期、结束日期返回这段时间里所有天的集合
def get_dates(start_date, end_date):
    dates = list()
    start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
    end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
    dates.append(start_date.strftime('%Y-%m-%d'))
    while start_date < end_date:
        start_date += datetime.timedelta(days=1)
        dates.append(start_date.strftime('%Y-%m-%d'))
    return dates

你可能感兴趣的:(Python,python,开发语言)