Home > Back-end >  How to Get all Day Names from a particular month
How to Get all Day Names from a particular month

Time:01-13

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']

CodePudding user response:

calendar.TextCalendar has a function to return the day and weekday index for each day in the month, but is listed per week in a list of lists. This can be used to generate your list using itertools.chain:

import calendar
import itertools

cal = calendar.TextCalendar()
print(cal.formatmonth(2021, 4))  # for reference
print(cal.monthdays2calendar(2021, 4))  # Function output
# processed...
myday = [calendar.day_abbr[wd] for d,wd in itertools.chain(*cal.monthdays2calendar(2021, 4)) if d]
print(myday)

Output:

     April 2021
Mo Tu We Th Fr Sa Su
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30

[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1), (14, 2), (15, 3), (16, 4), (17, 5), (18, 6)], [(19, 0), (20, 1), (21, 2), (22, 3), (23, 4), (24, 5), (25, 6)], [(26, 0), (27, 1), (28, 2), (29, 3), (30, 4), (0, 5), (0, 6)]]
['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', 'Wed', 'Thu', 'Fri']

CodePudding user response:

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)
  • Related