month | Month number for which dates are required |
year | Year number for which dates are required |
import calendar
my_cal= calendar.Calendar()
for x in my_cal.monthdays2calendar(2020,7):
print(x)
Output
[(0, 0), (0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
[(6, 0), (7, 1), (8, 2), (9, 3), (10, 4), (11, 5), (12, 6)]
[(13, 0), (14, 1), (15, 2), (16, 3), (17, 4), (18, 5), (19, 6)]
[(20, 0), (21, 1), (22, 2), (23, 3), (24, 4), (25, 5), (26, 6)]
[(27, 0), (28, 1), (29, 2), (30, 3), (31, 4), (0, 5), (0, 6)]
By updating the first day of the week we can get different elements of the list.
import calendar
my_cal= calendar.Calendar(firstweekday=0)
for x in my_cal.monthdays2calendar(2020,7):
print(x)
As we are getting a list as output, we can get total number of weeks in a month and number of days in a week. We are using len() here to get number of elements.
import calendar
my_cal= calendar.Calendar(firstweekday=0)
y=my_cal.monthdays2calendar(2020,7)
print("Number of weeks",len(y))
print("Number of days in week",len(y[0]))
Output
Number of weeks 5
Number of days in week 7
As we are getting a list of days as tuple for each week , we can display day and week day number like this.
import calendar
my_cal= calendar.Calendar(firstweekday=0)
for x in my_cal.monthdays2calendar(2020,7):
for y in x:
print("Day :",y[0],", Day of week",y[1])
Output
Day : 0 , Day of week 0
Day : 0 , Day of week 1
Day : 1 , Day of week 2
Day : 2 , Day of week 3
Day : 3 , Day of week 4
Day : 4 , Day of week 5
Day : 5 , Day of week 6
-----------------------
-----------------------
Day : 28 , Day of week 1
Day : 29 , Day of week 2
Day : 30 , Day of week 3
Day : 31 , Day of week 4
Day : 0 , Day of week 5
Day : 0 , Day of week 6
Calendar Module in Python itermonthdays()
itermonthdays2()
itermonthdays3()
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.