无法将整数与datetime.now()进行比较

时间:2017-08-26 15:38:32

标签: python python-3.x datetime time boolean

我正在尝试制作基于布尔和时间的程序。我试图做到这一点:

import datetime
now = datetime.datetime.now()
if int(00) and int(00) <= now.time and now.minute <= int(11) and int(59):
print ('morning')
elif int(12) and int(00) <= now.time and now.minute <= int(15) and int(59):
print ('afternoon')
elif int(16) and int(00) <= now.time and now.minute <= int(18) and int(59):
print ('evening')
elif int(19) and int(00) <= now.time and now.minute <= int(23) and int(59):
print ('good night')

但总是说

TypeError: '<=' not supported between instances of 'int' and 'builtin_function_or_method'

任何人都可以帮助我?

4 个答案:

答案 0 :(得分:0)

使用now.hour代替now.timenow.time()可以提供time个对象,而不是hour

if语句也似乎无效。期待可能

if int(00) <= now.hour and now.minute <= int(11) and now.seconds <= int(59): 
   print ('morning')

答案 1 :(得分:0)

我会这样做;)

from datetime import datetime

now = datetime.now()

if now.hour < 12:
    print ('morning')
elif now.hour < 16:
    print ('afternoon')
elif now.hour < 19:
    print ('evening')
else:
    print ('good night')

答案 2 :(得分:0)

在python中,你可以在if语句中使用x <= y <= z <= w语法:

1 <= 2 <= 3 < 4  # evaluates to True

仅检查小时,还简化了if语句

from datetime import datetime


def greeting(now=None):
    now = now or datetime.now()
    if 0 <= now.hour < 12:
        return 'morning'
    if 12 <= now.hour < 16:
        return 'afternoon'
    if 16 <= now.hour < 19:
        return 'evening'
    if 19 <= now.hour:
        return 'night'

print(greeting())  # 18:48:00 evening
print(greeting(datetime(2017, 8, 26, 22, 0, 0)))  # 22:00:00 night

答案 3 :(得分:0)

不确定这是否是您想要的:

{{1}}