Reputation: 45
I am trying to get all days of november as dates in november:
import calendar
calen = calendar.Calendar()
calen_iter = calen.itermonthdates(2017,11)
for c in calen_iter:
print (c)
I am getting the following output:
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
I dont want these dates - why do they appear?
2017-10-30
2017-10-31
2017-12-01
2017-12-02
2017-12-03
Upvotes: 3
Views: 818
Reputation: 124844
This is by design, see help(calen.itermonthdays)
(emphasis mine):
itermonthdates(year, month)
method ofcalendar.Calendar
instanceReturn 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.
Add a condition to filter out days from other months:
for c in calen_iter:
if c.month == 11:
print(c)
Or more compactly using a list comprehension:
days_of_november = [d for d in calen.itermonthdates(2017, 11) if d.month == 11]
Upvotes: 7