Day of week constants with Sunday = 0 in Python

kuzzooroo picture kuzzooroo · Feb 15, 2016 · Viewed 7.5k times · Source

The calendar module has day of week constants beginning with

calendar.MONDAY
Out[60]: 0

However, sometimes one must interface with a system (perhaps written in JavaScript) that uses the convention Sunday = 0. Does Python provide such constants?

Answer

Martijn Pieters picture Martijn Pieters · Feb 15, 2016

There are no such constants in the Python standard library. It is trivial to define your own however:

SUN, MON, TUE, WED, THU, FRI, SAT = range(7)

or, when using Python 3.4 or up, you could use the enum module functional API:

from enum import IntEnum

Weekdays = IntEnum('Weekdays', 'sun mon tue wed thu fri sat', start=0)

weekday == Weekdays.wed

and then you can then also map a weekday integer to an enumeration value by calling the enum.Enum object:

weekday_enum = Weekdays(weekday)

I used 3-letter abbreviations but you are free to use full names if you find that more readable.