datetime 给定时间内周的获取
import datetime def last_first_date_and_last_date(n): """ 获取前n周开始时间和结束时间,参数n:代表前n周 :param n: int类型 数字:1,2,3,4,5 :return: 返回前n周的周一0点时间 和 周日23点59分59秒 """ now = datetime.datetime.now() before_n_week_start = now - datetime.timedelta(days=now.weekday() + 7 * n, hours=now.hour, minutes=now.minute, seconds=now.second, microseconds=now.microsecond) before_n_week_end = before_n_week_start + datetime.timedelta(days=6, hours=23, minutes=59, seconds=59) return before_n_week_start, before_n_week_end def get_week_monday_and_sunday_by_date(date_str): """ 给定一个日期-返回日期所在周的周一0点时间 和 周日23点59分59秒 :param date_str: 如:"2020-05-01" :return: 给定一个日期-返回日期所在周的周一0点时间 和 周日23点59分59秒 """ now_time = datetime.datetime.strptime(date_str + " 00:00:00", "%Y-%m-%d %H:%M:%S") week_start_time = now_time - datetime.timedelta(days=now_time.weekday(), hours=now_time.hour, minutes=now_time.minute, seconds=now_time.second, microseconds=now_time.microsecond) week_end_time = week_start_time + datetime.timedelta(days=6, hours=23, minutes=59, seconds=59) return week_start_time, week_end_time def get_all_monday_and_sunday_by_date_interval(start_date_str, end_date_str): """ 给定时间(日期)区间,返回区间中所有的周起止时间列表(不含本周) :param start_date_str: "2020-01-31" :param end_date_str: "2020-05-08" :return: """ date_list = list() # 本周一开始时间 now = datetime.datetime.now() now_week_monday = now - datetime.timedelta(days=now.weekday(), hours=now.hour, minutes=now.minute, seconds=now.second, microseconds=now.microsecond) print('now_week_monday = {}'.format(now_week_monday)) # 起始时间所在周 - 周一和周日 start_week_monday, start_week_sunday = get_week_monday_and_sunday_by_date(start_date_str) print('start_week = {} -> {}'.format(start_week_monday, start_week_sunday)) # 截止时间所在周 - 周一和周日 end_week_monday, end_week_sunday = get_week_monday_and_sunday_by_date(end_date_str) print('end_week = {} -> {}'.format(end_week_monday, end_week_sunday)) if end_week_monday < now_week_monday: date_list.append({"start_time": end_week_monday, "end_time": end_week_sunday}) count = 1 while True: week_start_time = end_week_monday - datetime.timedelta(days=7 * count) week_end_time = week_start_time + datetime.timedelta(days=6, hours=23, minutes=59, seconds=59) print('middle_week = {} -> {}'.format(week_start_time, week_end_time)) count += 1 if week_start_time >= now_week_monday: continue if week_start_time < start_week_monday: break print('append middle_week = {} -> {}'.format(week_start_time, week_end_time)) date_list.append({"start_time": week_start_time, "end_time": week_end_time}) return date_list
摘自别人,只做备忘