从日期范围生成一周的开始和结束日期的列表

时间:2019-07-11 05:16:03

标签: python-3.x list

我正在尝试通过输入开始日期和结束日期来生成星期列表。 假设开始日期是 2019-05-01 ,结束日期是 2019-05-31 那么我想生成一个像这样的列表的列表

[['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']]

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用calendar内置模块(doc)来获取周数:

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)

打印:

[['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']]