gpt4 book ai didi

Python如何在没有其他月份日期的情况下迭代月份

转载 作者:行者123 更新时间:2023-12-05 01:44:05 26 4
gpt4 key购买 nike

我正在尝试将 11 月的所有日期作为 11 月的日期:

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

最佳答案

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

itermonthdates(year, month) method of calendar.Calendar instance

Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month.

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

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]

关于Python如何在没有其他月份日期的情况下迭代月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47252060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com