Search code examples
pythonpython-3.xlistcalendar

How to Get all Day Names from a particular month


Given a year and month, I want to print out the name of each day of the month, in order.

import calendar

weekday = calendar.weekday(2021,4)
myday = calendar.day_name[weekday]
print(myday)

Actual Output

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: weekday() missing 1 required positional argument: 'day'

Expected Output

['Mon','Tue','Wed','Thu','Fri','Sat','Sun','Mon','Tue','Wed','Thu','Fri','Sat','Sun','Mon','Tue','Wed','Thu','Fri','Sat','Sun','Mon','Tue','Wed','Thu','Fri','Sat','Sun','Mon','Tue']

Solution

  • the weekday() method takes as its arguments a year, a month and a day of month. From this data it works what day of week that single day falls on. You have only supplied a year and month, expecting the function to somehow loop through the entire month to give you a day of week. The method does not wok like that. I suggest:

    import calendar
    
    month_days = calendar.monthrange(2021, 4)
    
    myday = [calendar.day_name[calendar.weekday(2021, 4, i)] for i in range(1,month_days[1])]
    print(myday)