'Is there a function in Python that returns a number when it is given the day of the week as an input (string)?
The string "Monday" when passed to the function would return 0, and the string "Tuesday" would return 1 and so on and so forth...
Solution 1:[1]
You can get the attribute from the calendar module:
>>> import calendar
>>> getattr(calendar, "monday".upper())
0
Solution 2:[2]
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.
Solution 3:[3]
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
Solution 4:[4]
Create a dictionary of days:
import calendar
days = dict(zip(calendar.day_name, range(7)))
Look up the day:
>>> days["monday".title()]
0
Solution 5:[5]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bharel |
| Solution 2 | S.B |
| Solution 3 | |
| Solution 4 | |
| Solution 5 |
