Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a list of weekdays, starting with given weekday

My task is to define a function weekdays(weekday) that returns a list of weekdays, starting with the given weekday. It should work like this:

>>> weekdays('Wednesday')
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']

So far I've come up with this one:

def weekdays(weekday):
    days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
            'Sunday')
    result = ""
    for day in days:
        if day == weekday:
            result += day
    return result

But this prints the input day only:

>>> weekdays("Sunday")
'Sunday'

What am I doing wrong?

like image 761
Gusto Avatar asked Nov 02 '10 22:11

Gusto


People also ask

How does Python define weekday?

The weekday() method is used to returns the day of the week (0 is Monday) for year (1970–...), month (1–12), day (1–31). Year for which the calendar should be generated. month for which the calendar should be generated.

How do I get the last week start and end date in Python?

You can use datetime. timedelta for that. It has an optional weeks argument, which you can set to -1 so it will subtract seven days from the date . You will also have to subract the current date's weekday (and another one, to even the day since the Monday is 0 ).

How do I get the previous Monday date in Python?

You can find the next Monday's date easily with Python's datetime library and the timedelta object. You just need to take today's date. Then subtract the number of days which already passed this week (this gets you 'last' monday).


1 Answers

Your result variable is a string and not a list object. Also, it only gets updated one time which is when it is equal to the passed weekday argument.

Here's an implementation:

import calendar

def weekdays(weekday):
    days = [day for day in calendar.day_name]
    for day in days:
        days.insert(0, days.pop())    # add last day as new first day of list           
        if days[0] == weekday:        # if new first day same as weekday then all done
            break       
    return days

Example output:

>>> weekdays("Wednesday")
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
>>> weekdays("Friday")
['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
>>> weekdays("Tuesday")
['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday']
like image 81
Ray Avatar answered Oct 15 '22 04:10

Ray