Python 如何根据当天的不同显示不同的开放时间?

Python 如何根据当天的不同显示不同的开放时间?,python,datetime,time,Python,Datetime,Time,我从用户那里得到了yy-mm-dd格式的输入,从中我的程序应该决定是周一到周五还是周末。我有这样一段代码,我认为可以: def opening_hours(self, user_input): ''' Compare month and date of visit with the opening hours for the zoo :param user_input: input from user on the format yy-mm-dd :return:

我从用户那里得到了yy-mm-dd格式的输入,从中我的程序应该决定是周一到周五还是周末。我有这样一段代码,我认为可以:

def opening_hours(self, user_input):
    '''
    Compare month and date of visit with the opening hours for the zoo
    :param user_input: input from user on the format yy-mm-dd
    :return: user_input, day, opening_time_weekday, closing_time_weekday, opening_time_weekend, closing_time_weekend
    '''

    global day, opening_time_weekday, closing_time_weekday, opening_time_weekend, closing_time_weekend

    opening_time_weekday = 14
    closing_time_weekday = 20
    opening_time_weekend = 10
    closing_time_weekend = 22

    user_input = list(map(int, user_input.split('-')))
    day = datetime.date(user_input[0], user_input[1], user_input[2])
    print(day.weekday())

    if day.weekday == 0 or 1 or 2 or 3 or 4:
        print("The zoo is open from " + str(opening_time_weekday) + "-" + str(closing_time_weekday))
    else:
        print("The zoo is open from " + str(opening_time_weekend) + "-" + str(closing_time_weekend))


    return user_input, day, opening_time_weekday, closing_time_weekday, opening_time_weekend, closing_time_weekend
当我打印day.weekday时,它会打印正确的数字,因此,例如,如果我选择一个星期六的日期,它会打印5,因为这是第五天(从0开始),但代码仍然会始终打印“动物园从14-20开放”。有人能解释一下原因吗?

有趣的错误

    if day.weekday == 0 or 1 or 2 or 3 or 4:
由于
运算符的原因,这将不起作用。当您使用
A或B或C
时,这意味着测试
A
B
C
中的任何一项是否为
。因此在您的代码中,它总是正确的,因为
1
是正确的,所以Python甚至不会计算
案例的其余部分

请尝试以下方法:

    if day.weekday in (0, 1, 2, 3, 4):

问题出在您的
if
语句中。在Python中,如果1与
如果为True
相同。因此,当您执行
if day.weekday==0或1或2或3或4:
时,您说的是工作日是否为0或True或True或True,依此类推,这将始终为True(这就是or的工作方式)。正确的方法是
如果day.weekday==0或day.weekday==1或day.weekday==2等,这是相当长且重复的,或者更容易阅读,更简单的
如果day.weekday在[0,1,2,3,4]
如果day.weekday在范围(5)

您错误地使用了
运算符


if语句中的表达式的计算结果始终为True,因为1在Python中是一个truthy值。类似于
if day.weekday()的内容在范围(5)内:
将工作得更好。

您好,此
day.weekday==0或1或2或3或4
不正确。应该是[0,1,2,3,4]中的
day.weekday
您的pasring date方法非常简单,可能容易出错。考虑使用<代码> StpTime<代码> >代码>日期时间> DATESTIME/COD> >我会写“DATETIME.DATEIME.STRPIME”吗?我试过了,但是如何才能让用户输入[2]仍然可以使用它呢?现在它说这是一个意外的参数。您可以使用此
day=datetime.datetime.strtime(用户输入,“%y-%m-%d”)
将“yy-mm-dd”字符串转换为datetime对象。谢谢您的回答!我已经试过了,但是代码总是会打印出动物园从10-22(周末)开始开放,不管我输入的是哪一天。谢谢你的回答!我现在尝试编写“if day.weekday in range(5):”,但代码将始终打印出动物园从10-22(周末)开始开放,无论我键入哪一天。但是谢谢你的澄清!更新到
day.weekday()
就可以了!再次感谢!我忘了括号:)谢谢你的回答!我尝试了“if day.weekday in[0,1,2,3,4]”和“if day.weekday in range(5):”,但代码将始终打印出动物园从10-22(周末)开始开放,无论我键入哪一天。但是谢谢你的澄清!将if语句中的
day.weekday
更改为
day.weekday()
(就像您在print语句中所做的那样)。我应该在回答的时候注意到,对不起。哦,我都没想到。现在很好用,非常感谢!!没问题,如果您觉得这个答案有帮助,请接受带有绿色复选标记的答案
def test(foo):
   if foo == 0 or 1:
       print("The value is either 0 or 1")

test(2)
# The value is either 0 or 1