xtian
xtian

Reputation: 2947

Get the day of the week code (int) from proper name (string) with Python Standard Library

Is there a tricky cool way to get calendar.weekday(year, month, day) or datetime.weekday() (or something else in the PSL) to give you the day of the week code (int) from any of the standard proper names or abbreviations (str) for a day of the week word?

Or do I have to use this clunky dict?

>>> day_code = {'MO' : 0, 'TU' : 1, 'WE' : 2, 'TH' : 3, 'FR' : 4, 'SA' : 5, 'SU' : 6,
'MONDAY' : 0, 'TUESDAY' : 1, 'WEDNESDAY' : 2, 'THURSDAY' : 3, 'FRIDAY' : 4, 
'SATURDAY' : 5, 'SUNDAY' : 6, 'M' : 0, 'T' : 1, 'W' : 2, 'T' : 3, 'F' : 4, 'MON' : 0,
'TUE' : 1, 'WED' : 2, 'THU' : 3, 'FRI' : 4, 'SAT' : 5, 'SUN' : 6, 'TUES' : 1, 
'THUR' : 3, 'THURS' : 3}
>>> day_code['mon'.upper()]
0

Upvotes: 2

Views: 72

Answers (1)

Marsilinou Zaky
Marsilinou Zaky

Reputation: 1047

You can take advantage of string splitting in this case as follows

day_code = {'MO' : 0, 'TU' : 1, 'WE' : 2, 'TH' : 3, 'FR' : 4, 'SA' : 5, 'SU' : 6}
day = 'mon'
print(day_code[day[:2].upper()])

Upvotes: 1

Related Questions