简体   繁体   English

如何从Python的Datetime对象中查找工作日名称?

[英]How to find weekday name from the Python's Datetime object?

So I just started learning python and tried to make a program that tells you day on a given day. 因此,我刚刚开始学习python,并尝试编写一个程序来告诉您某天的某天。 I discovered datetime and tried to use it, but the problem is I am getting key error even though the key is present. 我发现了datetime并尝试使用它,但问题是即使存在密钥,我也遇到了密钥错误。

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. 您正在搜索一个int工作日数字,但是您应该检查字符串,因为字典中的键是str类型的。 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. 但是,您不需要dict对象即可根据关键日期获得工作日名称。 You may get the desired result via using .strftime('%A') on the datetime object as: 您可以通过在datetime对象上使用.strftime('%A')获得所需的结果,如下所示:

>>> datetime.datetime(1990,03,28).strftime("%A")
'Wednesday'

keys in your tags object are str values, however you convert them to int (which they already are) and then try to access value by int value, that's why you get KeyError . tags对象中的keysstr值,但是您将它们转换为int (它们已经是),然后尝试按int值访问值,这就是为什么要获取KeyError的原因。

Fix would be convert them to str and everything would work. 解决方法是将它们转换为str然后一切正常。

return tags[str(datetime.datetime(yy,mm,dd).isoweekday())]

isoweekday returns an integer. isoweekday返回一个整数。 The keys of your dictionary are strings. 字典的键是字符串。

You don't need to call int on the result as it is already an int - either replace that with str , or use integers as the keys of your dict. 您无需对结果调用int ,因为它已经是一个int了-将其替换为str ,或者使用整数作为dict的键。

尝试在查询字符串不是整数。

return tags[str(datetime.datetime(yy,mm,dd).isoweekday())]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM