[英]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.