Home > Back-end >  How to create a list of days of the week of the current month in Python?
How to create a list of days of the week of the current month in Python?

Time:12-11

I am pretty new to Python, and I am working on my third project, a calendar generator in Excel using Python. So I stuck on creating a function that would return a list of the weekdays [Monday, Tuesday, Wednesday...] of the current month. 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.

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.

CodePudding user response:

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

CodePudding user response:

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