[英]How to create a list of days of the week of the current month in Python?
I am pretty new to Python, and I am working on my third project, a calendar generator in Excel using Python.我对 Python 还很陌生,我正在研究我的第三个项目,一个使用 Python 的 Excel 中的日历生成器。 So I stuck on creating a function that would return a list of the weekdays [Monday, Tuesday, Wednesday...] of the current month.
所以我坚持创建一个 function ,它将返回当月的工作日列表 [周一、周二、周三...]。 I thought that maybe I could do this using for loop and slicing, however it doesn't work and most likely I will need to use datetime and calendar modules.
我想也许我可以使用 for 循环和切片来做到这一点,但是它不起作用,很可能我需要使用 datetime 和 calendar 模块。
Here is what I have now:这是我现在拥有的:
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
I would be super grateful if you could provide your thoughts on how to do this in the most basic way.如果您能提供有关如何以最基本的方式执行此操作的想法,我将非常感激。
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)]
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]]导入日历打印 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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.