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.itermonthdates(2020,7):
print(x)
Output
2020-06-29
2020-06-30
2020-07-01
2020-07-02
2020-07-03
2020-07-04
2020-07-05
2020-07-06
----------
----------
----------
2020-07-28
2020-07-29
2020-07-30
2020-07-31
2020-08-01
2020-08-02
By updating the first day of the week we can get different elements of the iterator.
import calendar
my_cal= calendar.Calendar(firstweekday=5)
for x in my_cal.itermonthdates(2020,7):
print(x)
Output
2020-06-27
2020-06-28
2020-06-29
2020-06-30
2020-07-01
2020-07-02
2020-07-03
----------
----------
----------
2020-07-25
2020-07-26
2020-07-27
2020-07-28
2020-07-29
2020-07-30
2020-07-31
We can use the object to display year , month and day
import calendar
my_cal= calendar.Calendar()
for x in my_cal.itermonthdates(2020,7):
print("Year:",x.year,", Month:",x.month,", Day :",x.day)
Output
Year: 2020 , Month: 6 , Day : 29
Year: 2020 , Month: 6 , Day : 30
Year: 2020 , Month: 7 , Day : 1
Year: 2020 , Month: 7 , Day : 2
Year: 2020 , Month: 7 , Day : 3
-------------------------------
-------------------------------
Year: 2020 , Month: 7 , Day : 29
Year: 2020 , Month: 7 , Day : 30
Year: 2020 , Month: 7 , Day : 31
Year: 2020 , Month: 8 , Day : 1
Year: 2020 , Month: 8 , Day : 2
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.