month | Month number for which dates are requried |
year | Year number for which dates are requried |
import calendar
my_cal= calendar.Calendar()
for x in my_cal.monthdatescalendar(2020,7):
print(x)
Output
[datetime.date(2020, 6, 29), datetime.date(2020, 6, 30), datetime.date(2020, 7, 1), datetime.date(2020, 7, 2), datetime.date(2020, 7, 3), datetime.date(2020, 7, 4), datetime.date(2020, 7, 5)]
[datetime.date(2020, 7, 6), datetime.date(2020, 7, 7), datetime.date(2020, 7, 8), datetime.date(2020, 7, 9), datetime.date(2020, 7, 10), datetime.date(2020, 7, 11), datetime.date(2020, 7, 12)]
[datetime.date(2020, 7, 13), datetime.date(2020, 7, 14), datetime.date(2020, 7, 15), datetime.date(2020, 7, 16), datetime.date(2020, 7, 17), datetime.date(2020, 7, 18), datetime.date(2020, 7, 19)]
[datetime.date(2020, 7, 20), datetime.date(2020, 7, 21), datetime.date(2020, 7, 22), datetime.date(2020, 7, 23), datetime.date(2020, 7, 24), datetime.date(2020, 7, 25), datetime.date(2020, 7, 26)]
[datetime.date(2020, 7, 27), datetime.date(2020, 7, 28), datetime.date(2020, 7, 29), datetime.date(2020, 7, 30), datetime.date(2020, 7, 31), datetime.date(2020, 8, 1), datetime.date(2020, 8, 2)]
By updating the first day of the week we can get different elements of the list.
import calendar
my_cal= calendar.Calendar(firstweekday=3)
for x in my_cal.monthdatescalendar(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.monthdatescalendar(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 date objects for each week , we can display month, year and day like this.
print("Day number of 4th element of first week: day,month,year \n",
y[0][4].day , y[0][4].month,y[0][4].year)
Output
Day number of 4th element of first week: day,month,year
3 7 2020
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.