5

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,...}
Isaac Philip
  • 498
  • 1
  • 5
  • 14

3 Answers3

12

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}
RahulHP
  • 336
  • 4
  • 6
  • 1
    To get a dictionary with the names as the keys, you need to reverse the order of the names and numbers: `d = dict(zip(calendar.day_name, range(7)))` or `d = {day: num for (num, day) in enumerate(calendar.day_name)}` – Matthias Fripp Jul 28 '16 at 07:51
0

It is unclear what you are asking for. If you want the day of the week for today, in text form, you could do this:

import datetime
print datetime.datetime.today().strftime('%A')

If you want to create a dictionary like the one you showed, you could do something like this:

import datetime
# make a list of seven arbitrary dates in a row
dates=[datetime.date.fromtimestamp(0) + datetime.timedelta(days=d) for d in range(7)]
# make a dictionary showing the names and numbers of the days of the week
print {d.strftime('%A'): d.weekday() for d in dates}
Matthias Fripp
  • 17,670
  • 5
  • 28
  • 45
0

The simple way to do this is with a dictionary comprehension and the calendar module.

import calendar
days = {name: i for i, name in enumerate(calendar.day_name)}
print(days)

output

{'Thursday': 3, 'Friday': 4, 'Tuesday': 1, 'Monday': 0, 'Wednesday': 2, 'Saturday': 5, 'Sunday': 6}

Python 2.6 and older do not have the dictionary comprehension, but you can pass a generator expression to the dict constructor.

days = dict((name, i) for i, name in enumerate(calendar.day_name))

It's also possible to make this dict with datetime, if you really want to. Eg,

from datetime import datetime, timedelta

oneday = timedelta(1)
day = datetime.today()
days = {}
for _ in range(7):
    days[day.strftime('%A')] = day.weekday()
    day += oneday

but using calendar is simpler & more efficient.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182