Quick question about template sensor

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"

Any help?

Please format your pasted code correctly. You’ve been a member for 4 years. You should know this. If not, see point 11 here: How to help us help you - or How to ask a good question

1 Like

Sorry, i fixed it

not quite, the first template is still unformatted.

Anyway, this works for me in a template editor

{{ ((now()|as_timestamp - states.binary_sensor.sensor.last_changed|as_timestamp) / 60) | round }}

and when you say

what does that mean?
btw, I think you don’t need entity_id in your template sensor.

I always put them in just to be safe.

1 Like

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 :wink:

I prefer explicit to implicit everytime

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.

2 Likes

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.

Thx i mainly need it for a node red flow