Problem with sensor and time

Good day everyone,
I’m trying to create a sensor that’s on from 9:00 AM to 1:00 AM and off the rest of the time. Using “greater than” and “less than” doesn’t work. How do I fix this? Thanks for your reply.

You need two conditions "or"ed together.

This reports false between 00:01 and 09:00 and true for all other hours. That’s suitable for a Template Binary Sensor.

{{ not 1 <= now().hour < 9 }}

If you need it to report on/off, you can do it like this:

{{  iif(not 1 <= now().hour < 9, 'on', 'off') }}

This looked odd to me:

So I checked the documentation:

The answer is actually saying, all times that are NOT between 1:00 AM and 9:00 AM

As such I would find the following syntax more readable:

{{ not (1 <= now().hour and now().hour < 9) }}

However given pythons operator precedence rules, both syntaxes will give the correct answer.

It’s been used in this forum throughout the years. It’s a compact way of indicating the variable’s value must be within the specified range. The expression places the variable directly between the range’s lower and upper limits.

Example

x must be greater than zero and less than one hundred.

{{ 0 < x < 100 }}