Python Calendar itermonthdays() Method with Example

Python Calendar.itermonthdays() Method: In this tutorial, we will learn about the itermonthdays() method of Calendar class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 24, 2023

Python Calendar.itermonthdays() Method

The Calendar.itermonthdays() method is an inbuilt method of the Calendar class of the calendar module, it returns an iterator for the given month in the given year. Days returned are the days of the month. Here, each week of the month a full 7 days, so if a day lies outside of the specified month, it is given a value of 0.

Module

The following module is required to use itermonthdays() method:

import calendar

Class

The following class is required to use itermonthdays() method:

from calendar import Calendar

Syntax

The following is the syntax of itermonthdays() method:

itermonthdays(year, month)

Parameter(s)

The following are the parameter(s):

  • year: It is a required parameter, which specifies the year of the calendar.
  • month: It is a required parameter, which specifies the month of the calendar.

Return Value

The return type of this method is <class 'generator'>, it returns an iterator for the given month which gives you the days of the month starting from the first weekday.

Example of Calendar.itermonthdays() Method in Python

# Python program to illustrate the 
# use of itermonthdays() method

# import class
import calendar

# Creating Calendar Instance
cal = calendar.Calendar()
year = 2009
month = 2
# Month starts with Sunday and weekday is set to 0
# So monday till saturday will be 0 and they represent 
# previous month days
print("Iterating over February 2009 where each value gives the day of the month")
for i in cal.itermonthdays(year, month):
    print(i)
print()


# Setting firstweekday value to 2
cal = calendar.Calendar(firstweekday = 2)
year = 2016
month = 12
# Month starts with Thursday and firstweekday is set to 2
# wednesday will be 0 and that represents 
# previous month day
print("Iterating over December 2016 where each value gives the day of the month")
for i in cal.itermonthdays(year, month):
    print(i)  

Output

Iterating over February 2009 where each value gives the day of the month
0
0
0
0
0
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
0

Iterating over December 2016 where each value gives the day of the month
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
0
0
0



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.