Template Binary Sensor Always - Day & Time Issue

I’m trying to create a template binary sensor that checks if the current time is between between a specified on & off time. So if its after the start time the sensor is true but, once the off time is reached the sensor is off again.

I’ve got the following which works fine:

- platform: template
  sensors:
    test_sensor_5:
      friendly_name: "test_sensor_5"
      value_template: >-
        {{  states("input_select.aquarium_light_off") >= now().time().strftime("%R") <= states("input_select.aquarium_light_off")  }}

However I only want this to work during workdays eg: The sensor is only on between 12:00 and 22:00hrs Mon -Fri. So, I added in what I thought was a simple “and” condition but this just sets the sensor to off 24/7.

- platform: template
  sensors:
    test_sensor_5:
      friendly_name: "test_sensor_5"
      value_template: >-
        {{ ( states("input_select.aquarium_light_off") >= now().time().strftime("%R") <= states("input_select.aquarium_light_off") ) and binary_sensor.workday_sensor == 'On' }}

Any ideas why this doesn’t work?

Thanks.

I think ‘On’ should actually be ‘on’

What micque said and you have to acquire the binary_sensor’s state (i.e. you can’t just do what you did: and binary_sensor.workday_sensor == 'on'

and states('binary_sensor.workday_sensor') == 'on'

There are some oddities in this template:

{{  states("input_select.aquarium_light_off") >= now().time().strftime("%R") <= states("input_select.aquarium_light_off")  }}

Effectively, it’s doing this:

A >= B <= A

Why? It’s checking if B is less than or equal to A twice.

In addition, that template contains one entity (an input_select). That means the template will be evaluated only when that one entity changes state. It won’t update for now() because it’s a function, not an entity. now() will not be used to evaluate (i.e. update/refresh) the template (actually, just once, at startup).

I tried that already. Thanks

Thats just a typo, the first is actually on and the second instance off.

I suspect the real issue is that I’m not grabbing the state of the workday sensor. I keep making that same simple mistake. Thanks for the extra set of eyes!

Thanks, I’ll give it a go using the correct state code.

First things first, fix the time issue I described. As it stands, your template will not be checked throughout the day.

If you add this:

  entity_id: 
    - sensor.time
    - input_select.aquarium_light_off
    - input_select.aquarium_light_on

then the template will be evaluated every minute because sensor.time changes state every minute (this assumes you have already defined sensor.time in your config).