Simple if then else but not working

I have this little code and it triggers, but the if then else part will never switch the switch? What am I missing, it used to work last year when it still was service_template now that has changed to Service but as said it will not fire the switch.
The if statement does work it gives true and falls when checked, so that is not so much the point.

here is the code for my Xmas lights:

id: '1639519145513'
alias: Kerstboom 2021
description: aan en uit
trigger:
  - platform: time
    at: '07:00:00'
  - platform: time
    at: '00:00:00'
condition: []
action:
  - service: |
      {% if 0 <= now().hour <= 7 %} 
        switch.turn_off
      {% else %}
        switch.turn_on
      {% endif %}
    entity_id: switch.sonoff_s20_2_relay
mode: single

what am I missing?

A trigger…
The way it’s set up now you might as well remove the if else since it can only ever be true.
The automation only triggers at 00:00 or 07:00 and both of these times the if part is true.

MMM let me see if I get you right.

So I should be better use a time pattern instead of the time trigger. Then there is the time between 0:00 and 7:00 set as being true! and triggered.

Or would the time trigger work if I used 1 minute past :slightly_smiling_face:

Even if you set the trigger to 07:01 then hour will still be 7 thus the if is true.

I would say it’s better to just have if hour == 0 then off, else on.
Because that way it will trigger at 00:00 and turn off, and it will trigger at 07:00 and the if will be false, so turn on.

Thank you Hellis, the words you used triggered the right response in my head, :slightly_smiling_face:

yes indeed there will nothing be triggered cause it is 7 am when the trigger triggers the if then else, it was blatant simple to see what was wrong but till I read what you said I did overlook this, it should have been:

service: |
  {% if 0 <= now().hour < 7 %} 
    switch.turn_off
  {% else %}
    switch.turn_on
  {% endif %}
entity_id: switch.sonoff_s20_2_relay

And now it fires beautifully, now I have an on and off in one automation, I like that more then for every light in my house that should go on and off on its own to have two automation’s.

1 Like

As I said before, this part:

  {% if 0 <= now().hour < 7 %} 

Could also be

  {% if now().hour == 0% } 

Because it will never trigger any other time of the day than 00:00 or 07:00 so there is no need to make a if statement that makes it harder to read than necessary in my opinion