Python datetime weekday number code - dynamically?

Isaac Philip picture Isaac Philip · Jul 28, 2016 · Viewed 9.1k times · Source

to get the weekday no,

import datetime
print datetime.datetime.today().weekday()

The output is an Integer which is within the range of 0 - 6 indicating Monday as 0 at doc-weekday

I would like to know how to get the values from Python

I wish to create a dictionary dynamically such as,

{'Monday':0, 'Tuesday':1,...}

Answer

RahulHP picture RahulHP · Jul 28, 2016

The following code will create a dict d with the required values

>>> import calendar
>>> d=dict(enumerate(calendar.day_name))
>>> d
{0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'}

Edit: The comment below by @mfripp gives a better method

>>> d=dict(zip(calendar.day_name,range(7)))
>>> d
{'Monday': 0, 'Tuesday': 1, 'Friday': 4, 'Wednesday': 2, 'Thursday': 3, 'Sunday': 6, 'Saturday': 5}