简体   繁体   English

在python中获取给定月份所有星期的开始和结束日期,不包括其他月份日期

[英]Get the start and end date of all the weeks for a given month in python exclusive of other months dates

I need to get the start and end dates of all the weeks for a given month in python.我需要在 python 中获取给定月份所有周的开始和结束日期。

Sample Input Dec 2018样本输入 2018 年 12 月

Possible outputs可能的输出

01-12-2018 01-12-2018

02-12-2018 - 08-12-2018 02-12-2018 - 08-12-2018

09-12-2018 - 15-12-2018 09-12-2018 - 15-12-2018

16-12-2018 - 22-12-2018 16-12-2018 - 22-12-2018

23-12-2018 - 29-12-2018 23-12-2018 - 29-12-2018

30-12-2018 - 31-12-2018 30-12-2018 - 31-12-2018

I used calendar module as follows,我使用日历模块如下,

obj_cal= calendar.Calendar(firstweekday=6)
[x for x in cal.monthdatescalendar(2018, 12)]

But this includes dates from 2018 Nov as well as from 2019 Jan但这包括 2018 年 11 月和 2019 年 1 月的日期

How to get exclusive of other month dates.如何排除其他月份的日期。

NB: Question edited注意:问题已编辑

Here is my solution:这是我的解决方案:

import calendar
from datetime import timedelta

# sunday is the first day of the week
# set 0 for monday
firstweekday = 6

def weeks_in_month(year, month):
    c = calendar.Calendar(firstweekday)
    for weekstart in filter(lambda d: d.weekday() == firstweekday, c.itermonthdates(year, month)):
        weekend = weekstart + timedelta(6)
        yield (weekstart, weekend)


for weekstart, weekend in weeks_in_month(2018, 12):
    print(weekstart, '-', weekend)

Output:输出:

2018-11-25 - 2018-12-01
2018-12-02 - 2018-12-08
2018-12-09 - 2018-12-15
2018-12-16 - 2018-12-22
2018-12-23 - 2018-12-29
2018-12-30 - 2019-01-05
>>> import datetime    
>>> import calendar
>>> cld=calendar.Calendar(firstweekday=0)
>>> for end_day in cld.itermonthdates(2018,12):
...     if end_day.weekday()==5:
...         start_day=end_day-datetime.timedelta(6)
...         print('{} - {}'.format(start_day.isoformat(),end_day.isoformat()))
... 
2018-11-25 - 2018-12-01
2018-12-02 - 2018-12-08
2018-12-09 - 2018-12-15
2018-12-16 - 2018-12-22
2018-12-23 - 2018-12-29
2018-12-30 - 2019-01-05

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM