How to get day of the week based on inputed date(Python)

Question:

So i wanted the user to enter date and based on that day to get named day of the week, for example today’s date is 2022.11.10, so wanted answer would be Thursday.
I know this is wrong, can anybody help?

import datetime

def dayOfTheWeek(day, month, year):
    date = datetime.date(year, month, day)
    weekday = date.weekday()
    day_dict = { 0 : "Monday", 1 : "Tuesday", 2 : "Wednesday", 3 : "Thursday", 4 : "Friday", 5 : "Sturday", 6 : "Sunday"}
    
    for key in day_dict.key():
        if weekday == key:
            return day[key]
        
year = int(input("Year: "))     
month = int(input("Month: "))       
day = int(input("Day: "))

dayOfTheWeek(day, month, year)

Answers:

Instead of going through the dictionary with for loop, you can simply return the result already converted by dictionary:

import datetime

def dayOfTheWeek(day, month, year):
    date = datetime.date(year, month, day)
    weekday = date.weekday()
    day_dict = { 0 : "Monday", 1 : "Tuesday", 2 : "Wednesday", 3 : "Thursday", 4 : "Friday", 5 : "Sturday", 6 : "Sunday"}

    return day_dict[weekday]
    
year = int(input("Year: "))     
month = int(input("Month: "))       
day = int(input("Day: "))

dayOfTheWeek(day, month, year)
Answered By: Jan Niedospial

Try this

from datetime import datetime

date = datetime(year=2022, month=11, day=10)  
weekday_name = date.strftime('%A')
print(weekday_name) 

See here for further information about strftime function.

Answered By: eelpcik
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.