yeardatescalendar() : Returns a list of months with full week and date object of the year .
import calendar
my_cal= calendar.Calendar()
for x in my_cal.yeardatescalendar(2020):
print(x)
The output is list of rows of months with full weeks and date objects. Based on the setting of firstweekday(), the first week of the year will start from previous year, last week and will extend up to next year’s first week.
List of month rows ( Number of months in a row is specified by width number )
Each Month contains list of full weeks ( 4 to 6 weeks in a month )
Each week contains 7 days ( objects )
You can check the output by removing the comment of different lines.
import calendar
my_cal= calendar.Calendar()
y= my_cal.yeardatescalendar(2020,2)
#print(y[1]) # list of month rows , it has 2 months
#print(y[0][1]) # list of full weeks of 2nd month
#print(y[1][0][0]) # list of days of first week
#print(y[1][0][0][1]) # 2nd date object of the first week
print("Year:",y[1][0][0][1].year,
", Month:",y[1][0][0][1].month, ", Day:",y[1][0][0][1].day)
Output ( last line only )
Year: 2020 , Month: 1 , Day: 28
We are getting output as list. So length or number of elements ( items ) present in the list ( iterable object) we can get by using len() function.
import calendar
my_cal= calendar.Calendar()
y= my_cal.yeardatescalendar(2020,2)
print("No. of months in the row : ", len(y[1]))
print("No. of full weeks in first month :",len(y[0][0]))
print("No. of days in first month, first week:",len(y[0][0][0]))
print("Second row, first month,first week,2nd day : ",y[1][0][0][1])
Output
List of months in the row : 2
List of full weeks in first month : 5
List of days in first month, first week: 7
Second row, first month,first week,2nd day : 2020-02-25
In above code the line y= my_cal.yeardatescalendar(2020,2) set the width to 2. So we are getting two months in a row or each element ( item ). So the output of first line len(y[1]) is 2
The first item of first row is the month, so the the len function len(y[0][0]) returns the number of full weeks in the month as 5.
We know each week has 7 days. So the value len(y[0][0][0]) returns 7.
Each week has date objects as element so we can get the respective year , month and day from the elements of the week y[1][0][0][1] gives us 2020-02-05.
Date Object
We are getting date object as elements ( item ) of the list, so we can display Year, Month and day from it.