What is itermonthdays() method from calendar in Python?
The itermonthdays() method returns an iterator of a specified month and year. Days returned will be day number.
This method is from the
calendarmodule. It is similar toitermonthdates().
Syntax
itermonthdays(year, month)
Parameters
This method takes two argument values:
year: year of the calendar.month: month of the calendar.
Return value
iterator: It returns an iterator of the specified month. For the days other than the specified month, the day number is 0.
We can use Python’s
iter()method to create an iterator instance.
Example 1
# Example#1# including calendar modulefrom calendar import Calendar# calendar instancecalendarObject = Calendar()# iterating with itermonthdaysfor day in calendarObject.itermonthdays(2022, 1):print(day)
Explanation
- Line 3: We load the
calendarmodule in the program. - Line 5: We instantiate the
Calendarclass from thecalendarmodule. - Line 7: We use the
itermonthdays()method, with year=2022 and month=1, to print the number of days in the specified month.
Example 2
# Example#2# including calendar modulefrom calendar import Calendar# defining argument valuesyear = 2021month = 4 # April# creating calendar instanceobj = Calendar()# iterating with itermonthdaysfor day in obj.itermonthdays(year, month):print(day)
Explanation
- Line 3: We include the
calendarmodule in the program. - Lines 5-6: We set the year=2021 and month=4.
- Line 8: We instantiate the
Calendarclass from thecalendarmodule. - Line 10: We use the
itermonthdays()method to print the number of days in the specified month and year to the console.