year | Year number for which dates are required |
width | Optional , default =3 , list of months in a row |
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.
[[[datetime.date(2019, 12, 30), datetime.date(2019, 12, 31),
datetime.date(2020, 1, 1), datetime.date(2020, 1, 2),
datetime.date(2020, 1, 3), datetime.date(2020, 1, 4),
datetime.date(2020, 1, 5)], [datetime.date(2020, 1, 6),
datetime.date(2020, 1, 7), datetime.date(2020, 1, 8),
datetime.date(2020, 1, 9), datetime.date(2020, 1, 10),
datetime.date(2020, 1, 11), datetime.date(2020, 1, 12)],
[datetime.date(2020, 1, 13), datetime.date(2020, 1, 14),
-----------------------------
-----------------------------
datetime.date(2020, 12, 30), datetime.date(2020, 12, 31),
datetime.date(2021, 1, 1), datetime.date(2021, 1, 2),
datetime.date(2021, 1, 3)]]]
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 len(y[0][0])
returns the number of full weeks in the month as 5.
len(y[0][0][0])
returns 7.
y[1][0][0][1]
gives us 2020-02-05.
import calendar
my_cal= calendar.Calendar()
y= my_cal.yeardatescalendar(2020,2)
print("Year : ",y[1][0][0][1].year,
", Month:",y[1][0][0][1].month,", Day :",y[1][0][0][1].day)
Output
Year : 2020 , Month: 2 , Day : 25
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.