Is there a function in Python that returns a number when it is given the day of the week as an input (string)?

Viewed 95

The string "Monday" when passed to the function would return 0, and the string "Tuesday" would return 1 and so on and so forth...

5 Answers

You can get the attribute from the calendar module:

>>> import calendar
>>> getattr(calendar, "monday".upper())
0

A simple way to do so is to create a dictionary:

d = {'Monday': 0, 'Tuesday': 1, 'Wednesday': 3, ...}

and then d['Monday'] would return 1. Wrap it into a function if you want.

If you don't want to use the calendar module and are only concerned with English names of weekdays:

def weekday_index(name):
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

    name = name.title()
    if name in days:
        return days.index(name)
        
    return -1

I would suggest using the calendar module. This offers the advantage of being locale independent.

import calendar

def get_day_num(day):
    try:
        return calendar.day_name[:].index(day.title())
    except ValueError:
        pass
    return -1

print(get_day_num('tuesday'))

Output:

1

Note:

print(get_day_num('dienstag'))

...would produce the same result in a German locale

Create a dictionary of days:

import calendar
days = dict(zip(calendar.day_name, range(7)))

Look up the day:

>>> days["monday".title()]
0
Related