Python如何与其他几个月的日期相关

时间:2017-11-12 17:57:45

标签: python date

我想把十一月的所有日子都当作十一月的日期:

import calendar

calen = calendar.Calendar()        
calen_iter = calen.itermonthdates(2017,11)

for c in calen_iter: 
    print (c)

我得到以下输出:

2017-10-30
2017-10-31
2017-11-01
2017-11-02
2017-11-03
<snipped lots of correct output>
2017-11-28
2017-11-29
2017-11-30
2017-12-01
2017-12-02
2017-12-03

我不想要这些日期 - 它们为什么会出现?

2017-10-30
2017-10-31
2017-12-01
2017-12-02
2017-12-03

1 个答案:

答案 0 :(得分:4)

这是设计,请参阅help(calen.itermonthdays)(强调我的):

  itermonthdates(year, month)实例

calendar.Calendar方法      

返回迭代器一个月。迭代器将产生datetime.date   值并且将始终迭代整个星期,因此它将产生   超出指定月份的日期

添加条件以过滤其他月份的天数:

for c in calen_iter: 
    if c.month == 11:
        print(c)

使用列表理解更紧凑:

days_of_november = [d for d in calen.itermonthdates(2017, 11) if d.month == 11]