[英]Python: Iterate over all days in a month
Is there a simple way to iterate over all days in a given month? 有没有一种简单的方法可以遍历给定月份中的所有天?
I would like to have a method where the object I'm iterating over has the days as datetime.date
objects. 我想有一个方法,其中我要遍历的对象将日期作为datetime.date
对象。 I have already found the calendar
module with its Calendar
class and respective method itermonthdates(year, month)
. 我已经找到了calendar
用模块Calendar
类和相应的方法itermonthdates(year, month)
。
My problem with this is that the resulting iterator contains "filler" days to represent complete weeks. 我的问题是,生成的迭代器包含代表整个星期的“填充”天。 For example July 2019 Ends on a Wednesday (31). 例如,2019年7月在星期三(31)结束。 so the week is incomplete and itermonthdates()
adds the dates 1-4 August. 因此该周是不完整的, itermonthdates()
将日期添加为8月1-4日。
I DO NOT want this behavior. 我不想要这种行为。
My first guess is something like: 我的第一个猜测是:
from calendar import Calendar, monthrange
c = Calendar()
for date in list(c.itermonthdates(2019, 7))[:monthrange(2019, 7)[1]]:
print(date)
which behaves as expected, but I'm not sure if there is a nicer, more elegant way of doing this. 它的行为符合预期,但是我不确定是否有更好,更优雅的方法。
只需按月过滤date
对象。
for d in [x for x in c.itermonthdates(2019, 7) if x.month == 7]:
The calendar
module is designed to display calendars. calendar
模块旨在显示日历。 You are better off using calendar.monthlen
in combination with datetime.date
itself to get your iterator, if you are looking for something straightforward: 如果您正在寻找简单的方法,最好将calendar.monthlen
与datetime.date
结合使用以获得迭代器:
def date_iter(year, month):
for i in range(1, calendar.monthlen(year, month) + 1):
yield date(year, month, i)
for d in date_iter(2019, 12):
print(d)
You can of course write the whole thing as a one-liner: 当然,您可以将所有内容写成单行:
for d in (date(2019, 12, i) for i in range(1, calendar.monthlen(2019, 12) + 1)):
print(d)
The monthlen
attribute appears to be a public, but undocumented attribute of calendar
in Python 3.7. monthlen
属性在Python 3.7中似乎是公共的,但未记录calendar
属性。 It is analogous to the second element of monthrange
, so you can replace it with monthrange(year, month)[0]
in the code above. 它类似于monthrange
的第二个元素,因此您可以在上面的代码monthrange(year, month)[0]
它替换为monthrange(year, month)[0]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.