How to convert a number to its correlating day of the week?

Question:

How do I convert a number to its correlating day of the week?

For example:

def string(hour_of_day, day_of_week, date) :
   print(f'{day_of_week} {date} at hour {hour_of_day}')

how can I re-write the ‘day_of_week’ part in print so that when I use the function:

string(12, 1, '2020/02/18') 

How can I get Tuesday 2020/02/18 at hour 12 instead of 1 2020/02/18 at hour 12?

Asked By: Mothy_Emms

||

Answers:

Use a dictionary along the lines of

daysdict = { 1: 'Monday', 2: 'Tuesday'} exetended for all the days

then access using daysdict[1]

Although your day 1 seems to be Tuesday!

It is possible to get the day directly from the date itself – something for you to check out.

Answered By: user19077881

Use calendar module

If you have already the weekday number, do:

import calendar

day_of_week = 1
calendar.day_name[day_of_week]
## 'Tuesday'

The calendar module is always available in Python (it is belongs to the inbuilt standard modules).

So the dictionary {0: "Monday", 1: "Tuesday", ...} is already defined as calendar.day_name. So no need to define it yourself. Instead type import calendar and you have it available.

Use datetime module to get weekday directly from the date

from datetime import datetime

def date2weekday(date):
    return datetime.strptime(date, "%Y/%m/%d").strftime('%A')

def myfunction(hour_of_day, date):
    return f"{date2weekday(date)} {date} at hour {hour_of_day}"

myfunction(12, '2020/02/18') 
## 'Tuesday 2020/02/18 at hour 12'


Answered By: Gwang-Jin Kim

You can use the strftime method from a datetime object:

import datetime

print(datetime.datetime(2022, 10, 21).strftime('%A %Y/%m/%d'))

It will give you this answer:

Friday 2022/10/21

To adapt it to your solution just do this:

from datetime import datetime

def string(hour_of_day, date):
    print(f'{date.strftime('%A %Y/%m/%d')} at hour {hour_of_day}')

string(12, datetime(year=2022, month=10, day=21))

The good thing about this solution is that you don’t need to know the day of the week of a date, Python already knows that, just ask him 😉

To know more about date formatting you can visit the datetime documentation in the official Python site

Answered By: alejandroklever
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.