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

2024-10-01 17:33:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在python中获取给定月份所有周的开始和结束日期。在

样本输入2018年12月

可能的输出

2018年12月1日

2018年12月2日-2018年12月8日

2018年12月9日-2018年12月15日

2018年12月16日-2018年12月22日

2018年12月23日-2018年12月29日

2018年12月30日-2018年12月31日

我使用日历模块如下:

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

但这包括2018年11月和2019年1月

如何排除其他月份的日期。在

NB:问题已编辑


Tags: 模块inobj编辑forcalendarcal样本
2条回答
>>> 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

我的解决方案是:

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)

输出:

^{pr2}$

相关问题 更多 >

    热门问题