Binary sensor based on time sensor

Hi,

I want to create a sensor based on another sensor (which I preferable do not want to see in the interface or log book).
Right now i have a sensor “LastActive” that gets updated everytime a sensor sends me something. I would like to have a boolean sensor instead named “Active” which is true if Last active is in the past 30 minutes and false otherwise.

Anyone who can point me in the right direction?

Post an example or two of this sensor’s value.

Here’s an example:

The UI can change the appearance of an entity’s datetime value so I need to see the actual datetime value which is displayed in Developer Tools > States. Go to that web page, find sensor.chinotto_lastactive and report its State value (the value may or may not be identical to what you already posted).

Found it.
Here’s the value:


2022-10-21T14:47:01+00:00

template:
  - binary_sensor:
      - name: Chinotto Active
        state: "{{ now() - states('sensor.chinotto_lastactive') | as_datetime < timedelta(minutes=30) }}"

This Template Binary Sensor reports on if the time difference between now and the time reported by sensor.chinotto_lastactive is less than 30 minutes (otherwise it reports off).

Seems to work. Thank you!

1 Like

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title and a link below your first post that leads to the Solution post. This helps users find answers to similar questions. For more information, refer to guideline 21 in the FAQ.

Alright, marked as answer.
Do you have any idea how I could change the text to “Yes” / “No” instead of “On” / “Off”?

Actually, I had suggested marking my post since that’s the one that provides the Solution. Your post simply contains a copy of what I proposed.

In some cases, you can use device_class to make the UI display on/off as other values. However, there’s nothing available for device_class that will display on/off as Yes/No. Therefore you will have to change it from a Template Binary Sensor to a Template Sensor.

template:
  - sensor:
      - name: Chinotto Active
        state: "{{ iif(now() - states('sensor.chinotto_lastactive') | as_datetime < timedelta(minutes=30), 'Yes', 'No') }}"

Thank you, also works. Will take some time to get used to this code within YAML syntax. :slight_smile:

It’s Jinja2 and there’s an introduction to it in the documentation section named Templating.