python-3.x 如何获取特定月份的所有日期名称

tquggr8v  于 2023-01-14  发布在  Python
关注(0)|答案(3)|浏览(131)

给定年和月,我想按顺序打印出该月每一天的名称。

import calendar

weekday = calendar.weekday(2021,4)
myday = calendar.day_name[weekday]
print(myday)
    • 实际产量**
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: weekday() missing 1 required positional argument: 'day'
    • 预期产出**
['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']
rn0zuynd

rn0zuynd1#

calendar.TextCalendar有一个函数可以返回一个月中每一天的日和工作日索引,但是它是按周列在列表列表列表中的。这可以用来使用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)

输出:

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

3wabscal2#

weekday()方法的参数是年、月和星期几。2根据这些数据,它可以计算出那一天福尔斯星期几。3你只提供了年和月,期望函数循环遍历整个月,给予一个星期几。4这个方法不是这样工作的。5我建议:

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)
hlswsv35

hlswsv353#

import calendar
year=int(input("Enter year in the form of yyyy : "))
month=int(input("Enter month in the form of mm : "))

month_days = calendar.monthrange(year,month)
dayscalofmonth = [
    calendar.day_name[calendar.weekday(year,month, i)] 
    for i in range(1,month_days[1])]
print(dayscalofmonth)
# display the calendar
print(calendar.month(year, month))

相关问题