from datetime import timedelta, datetime
from typing import List
from typing import Tuple
import copy

def generate_week_date_intervals(start_date: datetime, num_weeks: int) -> List[Tuple]:
    """
    Generate intervals for weeks returning tuples of (start_date, end_date) for each week.
    E.g. if today is tuesday and I request a date interval for only this week, it will return the date for 
    next monday as the end_date and yesterday (Monday) as the start_date. 
    :param start_date: today's date
    :param num_weeks: 1 means this week only, 2 means this week and last week etc.
    :return: 
    """
    next_monday = get_next_monday_date(start_date)
    print(type(next_monday))
    # ns = list(map(lambda x: x + 1, range(num_weeks)))  # [1, 2, 3, etc]
    ns = list(range(num_weeks + 1))  # [0, 1, 2, 3, etc]
    all_dates = list(map(lambda n: subtract_n_weeks(next_monday, n), ns))
    start_dates = copy.deepcopy(all_dates)[:-1]
    end_dates   = copy.deepcopy(all_dates)[1:]
    return list(zip(start_dates, end_dates))


def get_next_monday_date(date: datetime) -> datetime:
    days_til_monday: int = 7 - date.weekday()
    return date + timedelta(days=days_til_monday)


def subtract_n_weeks(date: datetime, n_weeks: int) -> datetime:
    return date + timedelta(weeks=-n_weeks)

Leave A Comment

Related Post

Read More
Read More
Read More
Read More