Skip to content Skip to sidebar Skip to footer

Generate List Of List For Start And End Date Of Week From Date Range

I'm trying to generate week list by entering the start date and end date. Let's say if the start date is 2019-05-01 and end date is 2019-05-31 then I would like to generate a list

Solution 1:

You could use calendar builtin module (doc) for getting the weeks:

import calendar
from datetime import datetime, timedelta

def get_all_weeks(start_date, end_date):
    start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
    end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
    one_day, one_week = timedelta(days=1), timedelta(days=7)
    current_week_start = calendar.Calendar().monthdatescalendar(start_date.year, start_date.month)[0][0]
    while True:
        if current_week_start + one_week <= start_date:
            current_week_start += one_week
            continue
        if current_week_start > end_date:
            break
        yield [current_week_start.strftime('%Y-%m-%d'), (current_week_start + one_week - one_day).strftime('%Y-%m-%d')]
        current_week_start += one_week

d_start = '2019-05-01'
d_end = '2019-05-31'

weeks = [*get_all_weeks(d_start, d_end)]

from pprint import pprint
pprint(weeks)

Prints:

[['2019-04-29', '2019-05-05'],
 ['2019-05-06', '2019-05-12'],
 ['2019-05-13', '2019-05-19'],
 ['2019-05-20', '2019-05-26'],
 ['2019-05-27', '2019-06-02']]

Post a Comment for "Generate List Of List For Start And End Date Of Week From Date Range"