User avatar
marciokoko
Posts: 276
Joined: Sat Aug 27, 2016 4:33 pm

If else code for time domain

Thu Oct 18, 2018 1:16 am

<t>So I want the rpi3 connected to my relay board to turn lights on and off. I have the on time at 17 hrs and the off time at 6 hrs.

My code is:

Code: Select all

        def relayToggle(self):

                timestringON = AIHome.results['Relay1ON']
                timestringOFF=AIHome.results['Relay1OFF']
                print timestringON
                print timestringOFF
                hoursON,minutesON = timestringON.split(":")
                hoursOFF,minutesOFF= timestringOFF.split(":")
                print hoursON
                print hoursOFF
                print(datetime.datetime.now())
                #ref_time = datetime.datetime.combine(datetime.datetime.now(), d$
                presentTime=datetime.datetime.now()
                presentHour=presentTime.hour
                if int(hoursON) > int(presentHour) & int(hoursOFF) <= int(presen$
                        print("ref_time>>relay should be OFF")
                        self.write(1,0)
                else:
                        print("now>>relay should be ON")
                        self.write(1,1)
So Im getting now at 19:14 that relay should be off:

ON=17
OFF=6
present=19

17 > 19 FALSE, so it should go to the else, but it doesnt. Why?

User avatar
Paeryn
Posts: 2168
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: If else code for time domain

Thu Oct 18, 2018 2:21 am

When copying code out of your editor it doesn't help that you miss off the ends of lines, I've added what I assume the end of the line was.
marciokoko wrote:
Thu Oct 18, 2018 1:16 am

Code: Select all

if int(hoursON) > int(presentHour) & int(hoursOFF) <= int(presentHour):
So Im getting now at 19:14 that relay should be off:

ON=17
OFF=6
present=19

17 > 19 FALSE, so it should go to the else, but it doesnt. Why?
Because & is the bitwise operator, and is the boolean operator. What you have is

Code: Select all

if 17 > (19 & 6) <= 6:  # if 17 > 2 <= 6:
19 & 6 = 2.
17 is greater than 2 and 2 is less than 6 so the condition is True.
What you wanted was

Code: Select all

if int(hoursON) > int(presentHour) and int(hoursOFF) <= int(presentHour):
She who travels light — forgot something.

Return to “Beginners”