Template Entities and last_changed/last_updated

Hello. I have made a sensor that keeps track of the last time my cat has eaten based on certain factors around my house. Works splendidly. The question I have is how do I get it to ignore Home Assistant restarts when I use last_changed or last_updated? This template works great until restart of HA or reload of template entities. Then they show the time I restarted or reloaded.

    - name: Pants - Last Fed
      state: >
        {{ states.binary_sensor.pants_eating.last_changed | as_local | as_timestamp | timestamp_custom('%D %-I:%M %p') }}
    - name: Pants - Last Fed
      state: >
        {{ states.binary_sensor.pants_eating.last_updated | as_local | as_timestamp | timestamp_custom('%D %-I:%M %p') }}

Both do the exact same thing though.
Any ideas?

Store the time in an input_datetime instead.

Thank you. This should be what I am needing. You rock. I’ll test it out and if works, mark as solution.

So because the automation that causes the input_datetime to update relies on a template entity as well, this will not work, because every time I restart HA, it triggers that automation… :frowning:

I haven’t tested this but try triggering the automation on shutdown.

  trigger:
    - platform: homeassistant
      event: shutdown

Whether it works or not will depend on whether Home Assistant will allow your automation to reliably update the input_datetime just moments before it shuts down. :thinking:

As for your existing trigger that monitors the sensor’s last_changed value, you’ll need to add a time constraint that prevents it from updating the input_datetime if Home Assistant started just seconds earlier (because that’s when it forces the sensor’s last_changed to the current time). The Uptime integration is useful for determining how much time has elapsed since startup.

1 Like

@123 thank you for getting my mind thinking again. I was in the process of trying to incorporate the Uptime integration, which is a great idea, when I realized, um… triggers…


- trigger:  ##Pants Last Ate## 
    - platform: template
      value_template: >
        {{ states.binary_sensor.pants_eating.state == 'on' }}
  sensor:
    - name: Pants Last Ate
      state: >
        {{ states.binary_sensor.pants_eating.last_changed }} 

Boom Solved.

2 Likes