【实用】得到三个动态时间点作为分界点

因为周报需要对比上周,所以现在有一个需求,动态生成上周周一的时间点,类似 ‘2023-10-23 00:00:00’ 并将值赋予给time2变量,将time2 减去7天,得到的时间点赋值给time1,将time2 减去7天,得到的时间点赋值给time3,得到三个动态时间点作为分界点;

# WEEKDAY函数返回一个日期的工作日索引值,即星期一为0,星期二为1,星期日为6
SET @time2 := CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY - INTERVAL 7 DAY;
SET @time1 := @time2 - INTERVAL 7 DAY;
SET @time3 := @time2 + INTERVAL 7 DAY;

SELECT @time1 AS time1, @time2 AS time2, @time3 AS time3;


在这里插入图片描述

from datetime import date, timedelta, datetime

def generate_last_week_dates():

    current_datetime = datetime.now()

    # 获取上周周一的日期 : datetime.now().weekday() 返回从0开始的数字,比如今天是星期5,那么返回的就是4
    last_week_monday = current_datetime - timedelta(days=current_datetime.weekday() + 7)
    last_week_monday = last_week_monday.replace(hour=0, minute=0, second=0, microsecond=0)
    
    time2 = last_week_monday.strftime('%Y-%m-%d %H:%M:%S')
    time1 = (last_week_monday - timedelta(days=7)).strftime('%Y-%m-%d %H:%M:%S')
    time3 = (last_week_monday + timedelta(days=7)).strftime('%Y-%m-%d %H:%M:%S')

    return time1, time2, time3

time1,time2,time3 = generate_last_week_dates()
('2023-10-16 00:00:00', '2023-10-23 00:00:00', '2023-10-30 00:00:00')

你可能感兴趣的:(Python,数据库,python)