[英]Can't compare integers with datetime.now()
我正在尝试制作基于布尔和时间的程序。 我试图做到这一点:
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'
有人可以帮助我吗?
使用now.hour
而不是now.time
。 now.time()
可以提供time
对象,而不是hour
。
并且对于if
语句似乎也是无效条件。 期望也许
if int(00) <= now.hour and now.minute <= int(11) and now.seconds <= int(59):
print ('morning')
我认为这可以做到;)
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')
在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
不确定这是否是您想要的:
import datetime
# Define hours that different times of day start
start_of_afternoon = 12
start_of_evening = 16
start_of_night = 19
# Get current time
now = datetime.datetime.now()
if now.hour < start_of_afternoon: # before 12pm
print ('morning')
elif start_of_afternoon <= now.hour and now.hour < start_of_evening: # after 12pm and before 4pm
print ('afternoon')
elif start_of_evening <= now.hour and now.hour < start_of_night: # after 4pm and before 7pm
print ('evening')
elif start_of_night <= now.hour: # after 7pm
print ('good night')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.