Different results in template vs sensor output

I dumped the following in the templating editor (as well as defined the sensor from the text within


   ac_last_changed:
    friendly_name: 'AC Last Changed From Present'
    unit_of_measurement: 'seconds'
    value_template: >-
      {% set CONTROL = 'sensor.be469zp_connect_smart_deadbolt_access_control' %}
      {% set CONTROLlc = states.sensor[CONTROL.split('.')[-1]].last_changed %}
      {{ as_timestamp(now()) - as_timestamp(CONTROLlc) }}

AC Sensor {{ states.sensor.ac_last_changed.state }}    

Here is the template output:


ac_last_changed:
    friendly_name: 'AC Last Changed From Present'
    unit_of_measurement: 'seconds'
    value_template: >-
      
      
      231.27665901184082

AC Sensor 1.457772970199585

Everytime I modify the template code, I see the value_template “update” with the difference between “now()” and the last changed time for sensor.be469zp_connect_smart_deadbolt_access_control. This is the expected and desired behavior. However the value for ac_last_changed is not changing. What am I doing wrong?

What I’m attempting to do is create a sensor that returns the number of seconds from the current time that the entity was last changed. I have several other things I want to use this value, such as making sure the last_changed property changed within 5 seconds in one automation and 30 in another.

Pinging @freshcoast and @arsaboo as they commented on a similar issue

The solution was interesting. Create an automation that forces the sensor(s) to update every second. By calling update_entity this makes now() report correctly in the templating engine.


    - alias: 'ac-uc-sensors_last_changed_update'
      trigger:
        - platform: time_pattern
          seconds: '/1'
      action:
        - service: homeassistant.update_entity
          entity_id: sensor.ac_last_changed
        - service: homeassistant.update_entity
          entity_id: sensor.uc_last_changed

Some minor suggestions.

You should be able to combine the service calls and pass the entities as a list.

    - alias: 'ac-uc-sensors_last_changed_update'
      trigger:
        - platform: time_pattern
          seconds: '/1'
      action:
        - service: homeassistant.update_entity
          entity_id:
            - sensor.ac_last_changed
            - sensor.uc_last_changed

Your template sensor seems to be more complicated than necessary?

   ac_last_changed:
    friendly_name: 'AC Last Changed From Present'
    unit_of_measurement: 'seconds'
    value_template: >-
      {{ as_timestamp(now()) - as_timestamp(states.sensor.be469zp_connect_smart_deadbolt_access_control.last_changed) }}