So I just started learning python and tried to make a program that tells you day on a given day. I discovered datetime
and tried to use it, but the problem is I am getting key error even though the key is present.
Here's my code:
import datetime
def day_finder(dd,mm,yy):
tags = { '1' : 'Monday' ,'2' : 'Tuesday' ,'3' : 'Wednesday' ,'4' : 'Thursday' ,'5' : 'Friday' ,'6' : 'Saturday' ,'7' : 'Sunday' }
return tags[int(datetime.datetime(yy,mm,dd).isoweekday())]
d = int(input("Enter a date"))
m = int(input("Enter a month"))
y = int(input("Enter a year"))
print (day_finder(d,m,y))
You are searching for an int
weekday number, but instead you should be checking for the string because the keys in your dictionary are of str
type. For example:
>>> tags = { '1' : 'Monday' ,'2' : 'Tuesday' ,'3' : 'Wednesday' ,'4' : 'Thursday' ,'5' : 'Friday' ,'6' : 'Saturday' ,'7' : 'Sunday' }
>>> import datetime
>>> tags[str(datetime.datetime(1990,03,28).isoweekday())]
'Wednesday'
However, you do not need a dict
object to get the weekday name based on the key day number. You may get the desired result via using .strftime('%A')
on the datetime
object as:
>>> datetime.datetime(1990,03,28).strftime("%A")
'Wednesday'