Template evaluation, strange thing. What am I missing?

Hi reader :slight_smile:

I am trying to use the template binary sensor in order to mix two values in a evaluation (True/False)

my idea is to have a binary sensor that tells me if it’s sleeping time. It is used for turning on or changing the lights color.

 binary_sensor:
  • platform: template
    sensors:
    late_night_sensor:
    value_template: >-
    {% if is_state(‘binary_sensor.workday’, ‘True’) %}
    {{ strptime(“00:10”, “%H%M”) < now().strftime("%H:%M")
    and now().strftime("%H:%M") < strptime(“08:00”, “%H%M”) }}
    {% else %}
    {{ strptime(“00:10”, “%H%M”) < now().strftime("%H:%M")
    and now().strftime("%H:%M") < strptime(“09:30”, “%H%M”) }}
    {% endif %}

I tried a couple of variation of this template but in some way it is not working correctly.
If it starts with a ON value it stays always ON and if it starts with OFF it stays always OFF.

What can I do for have a ON for a range of time and false for the other time?

strings don’t evaluate as numbers. You are trying to compare a string to a number.

seems like you want it to return tru between midnight and 8am on weekdays and midnight and 930 am on weekends.

Try this:

platform: template
sensors:
  late_night_sensor:
    {% set end = 8.0 if is_state('binary_sensor.workday', 'True') else 9.5 %}
    {{ ( 10 / 60 ) < now().hour + now().minute / 60 < end }}

Everything is converted to hours, thats why minutes are divided by 60. So this may work for you. FYI sensors like these may not update often because it’s based on the state change for binary_sensor.workday. You may want to attach an entity id to it to allow it to update more often.

Your other option is to use the sensor.time platform and swap that out for now().hour + now().minute / 60.

In that case, you have to use strptime:

platform: template
sensors:
  late_night_sensor:
    {% set t  = strptime(states('sensor.time'), '%H:%M') %}
    {% set end = 8.0 if is_state('binary_sensor.workday', 'True') else 9.5 %}
    {{ ( 10 / 60 ) < t.hour + t.minute / 60 < end }}

Hi petro,

thank you for your kind reply.
Yes, that’s correct, basically I would like to define a time delta that I can define as “sleep time” in order to use it in other calculation using a bayesian sensor. My previous version of the template does not use the workday so it was always in the range “midnight” - 8 AM. That has the problem that on sunday the automation start too early.

I will try your suggestion and let you know. Thank you really much for your example.
I have some doubt related to the understanding related to when the template is re-evaluated. I will try to better understand that.
I didn’t found any reference related to when a template is evaluated yet.

There isn’t much documentation. I’ve debugged into the code and it appears to only update when referenced entities update. You can provide reference entities in template sensors so that may work as well.