If I enter the following in developers tools template i get the minutes that have passed since the door was closed. When I use it as a template sensor i get 0.
This works:
{{ ((as_timestamp(now())-as_timestamp(states.binary_sensor.sensor.last_changed))/60) | round | int }}
This doesnt:
- platform: template
sensors:
door_closed_since:
entity_id: binary_sensor.sensor
value_template: "{{ ((as_timestamp(now())-as_timestamp(states.binary_sensor.sensor.last_changed))/60) | round | int }}"
friendly_name: "Time since Door was closed"
it’s perfectly valid but can be a pita when you change your template and forget about entity_id.
I prefer to stick to the rules HA uses to detect entities to listen to and it saves me from this pain
It’ll always be zero unless you add a sensor that updates regularly. It’s zero because the template sensor is only updating when binary_sensor.sensor updates. When that call is performed, the time difference is near zero because now will pretty much equal last_changed.
The solution would be to integrate sensor.time and add that to the entity_id list. Then it will update every minute and when binary_sensor.sensor updates.
EDIT: Another solution would be to use the timestamp sensor device class:
- platform: template
sensors:
door_closed_since:
entity_id: binary_sensor.sensor
value_template: "{{ as_timestamp(states.binary_sensor.doorbell_button.last_changed) | timestamp_custom('%Y-%m-%dT%H:%M:%S.%f+00:00', False) }}"
device_class: timestamp
friendly_name: "Time since Door was closed"
This sensor will always show the correct time. But you’ll only be able to use it in cards that properly display the information: Glance, entities, and a few others. But custom cards like custom:button-card will not work.
I liked this, I’d like it more but you can’t do that.
The reason I liked it was because it is so obvious in hindsight (but most solutions are like that) AND I was too blind to see it.