Reputation: 845
I need to execute a code between a set time every day. So I need to find if the current time is between a time range.
hralarm=False
now = datetime.datetime.now().time()
if datetime.time(hour=14,minute=40) > now > datetime.time(hour=14,minute=50):
hralarm=True
else :
hralarm=False
The hralarm flag is always returning a False. The now variable returns 14:46:22.994000 . Should I format 'now' to not have the seconds and microseconds and maybe that is why the comparison is not happening correctly?..I am new to python so any help would be greatly appreciated.
Upvotes: 0
Views: 60
Reputation: 9
import time
import datetime
hralarm=False
now = datetime.datetime.now().time()
time1 = datetime.time(14, 40, 0)
time2 = datetime.time(14, 50, 0)
if (time1.hour >= now.hour and time1.minute < now.minute) and (now.hour <= time2.hour and now.minute < time2.minute):
hralarm=True
else :
hralarm=False
print(hralarm)
Upvotes: -1
Reputation: 1125398
You have your comparison operators mixed up. You are asking if the current time is before 14:40:
datetime.time(hour=14,minute=40) > now # only times *smaller* will match
and after 14:50:
now > datetime.time(hour=14,minute=50) # only times *greater* will match
No clock time can ever match both those conditions at the same time.
The following test would work to find times between 14:40 and 14:50 however:
if datetime.time(14, 40) < now < datetime.time(14, 50):
# 14:40 must be smaller and 14:50 must be greater
Remember that the 'pointed' end of a <
or >
points to the smaller value.
Note that the comparison operators already produce True
or False
, you can assign that directly to your hralarm
variable rather than use if
to confirm it for you:
now = datetime.datetime.now().time()
hralarm = datetime.time(14, 40) < now < datetime.time(14, 50)
Upvotes: 3
Reputation: 845
hralarm=False
now = datetime.datetime.now().time()
if datetime.time(hour=14,minute=40) < now < datetime.time(hour=14,minute=50):
hralarm=True
else :
hralarm=False
Upvotes: -1