What's wrong with my late_night sensor template?

- platform: template
  sensors:
    late_night_sensor:
      value_template: >-
          {{ strptime("22:00", "%H%M")  < now().strftime("%H:%M")
             or now().strftime("%H:%M") < strptime("06:30", "%H%M") }}

It’s currently 09:55 in the morning here and late_night_sensor is currently on. My understanding is that it should be off when the time is not between 22:00 -> 06:30. What am I missing?

now() does not update templates. See the warning here : https://www.home-assistant.io/docs/configuration/templating/#templates-without-entities-using-now

It’s a mistake nearly everyone makes when beginning with templates. That warning should really be in 100pt flashing red font.

Add an entity to update the template, like the time sensor (updates every minute):

- platform: template
  sensors:
    late_night_sensor:
    entity_id: sensor.time
      value_template: >-
          {{ strptime("22:00", "%H%M")  < now().strftime("%H:%M")
             or now().strftime("%H:%M") < strptime("06:30", "%H%M") }}

Thank you! I noticed the warning in the log right before you posted and reckoned it was the cause of the issue.

Thanks again!

You’re also trying to compare datetime objects to strings, which isn’t going to work. And your use of strptime isn’t correct (so you’re not really getting datetime objects anyway.)

Try this:

- platform: template
  sensors:
    late_night_sensor:
    entity_id: sensor.time
      value_template: >
        {{ not (strptime("06:30", "%H:%M").time() <= now().time() <=
                strptime("22:00", "%H:%M").time()) }}
1 Like

That seems to work! Thank you.

1 Like

Actually, it doesnt work either.

- platform: template
   sensors:
     late_night_sensor:
       friendly_name: "Late Night Sensor"
       entity_id: sensor.time
       value_template: >
         {{ not (strptime("06:30", "%H:%M").time() <= now().time() <=
                 strptime("22:00", "%H:%M").time()) }}

The sensor has been on from 03:53 - 09:07 and off since. Seems very arbitrary and I am totally confused.

Have you defined sensor.time in your configuration? Do you see sensor.time listed on the States page?

Well, no. From the docs I assumed that was not necessary.

Useful entities to choose might be sensor.date which update once per day or sensor.time which updates once per minute.

The sensor has to exist for it to create state_changed events. If it doesn’t, just referencing it will do nothing.

That makes sense. So how exactly would I define it if I might ask?

EDIT: I reckon this will do:

# Time
  - platform: time_date
    display_options:
      - 'time'