【问题标题】:How to create a list of days of the week of the current month in Python?如何在 Python 中创建当月星期几的列表?
【发布时间】:2022-01-15 13:09:46
【问题描述】:

我对 Python 还是很陌生,我正在做我的第三个项目,一个使用 Python 的 Excel 日历生成器。所以我坚持创建一个函数,该函数将返回当月的工作日列表 [周一、周二、周三...]。我想也许我可以使用 for 循环和切片来做到这一点,但是它不起作用,很可能我需要使用 datetime 和 calendar 模块。

这是我现在拥有的:

l1 = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

def weekdays(start_day, weeks_in_month):
    weekdays_list = []
    for days in range(weeks_in_month):
        weekdays_list.append(l1[start_day:])
    return weekdays_list

如果您能提供有关如何以最基本的方式执行此操作的想法,我将非常感激。

【问题讨论】:

  • 您希望weekdays_list 包含什么内容?请包括一个示例输入和所需的输出。
  • @wwii 我希望 weekdays_list 包含工作日列表,即 [Monday, Tuesday, Wednesday....]
  • How to get day name from datetime 回答你的问题了吗?

标签: python datetime calendar


【解决方案1】:
import calendar
print calendar.monthcalendar(2013, 4)
[[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, 0, 0]]

【讨论】:

    【解决方案2】:
    import itertools
    
    # python naming convention uses UPPERCASE for constants
    WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday",
                "Friday", "Saturday", "Sunday"]
    
    # let's use number of days instead of weeks so we can handle
    # fractional weeks
    def weekdays(start_day, num_days):
        # create a cycling iterator to simplify wrapping around weeks
        day = itertools.cycle(WEEKDAYS)
    
        # skip the iterator forward to start_day
        for _ in range(WEEKDAYS.index(start_day)):
            next(day)
    
        # generate the list of days using a list comprehension
        return [next(day) for _ in range(num_days)]
    

    itertools.cycle

    【讨论】:

      猜你喜欢
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      相关资源
      最近更新 更多