Trigger based template sensor to retrieve last change of an entity

To retrieve the date and time an entity had it last change, there is a last_changed property in the state object. However, after a restart of Home Assistant, this will be reset to the time HA started.

Note:

  • The configuration below will only store nominal state changes, so it will not store state changes from or to unavailable or unknown. So it can’t be used to track when an entity became unavailable. You could remove the not_to: part to also store those changes, however, you won’t be able to see when they came back online then. Generally entities are first unavailable after a restart, so when you also remove the not_from part, you will have the same issue as the last_changed property has.
  • There is a limitation how much data you can store in an attribute. If it becomes too big, it will not be stored in the database, and can therefor not be retrieved. If you really want to store a lot of data, you can maybe split the entities over several sensors.

Sensor configuration

Just add all the entities you want to track to the trigger.

template:
  - trigger:
      - platform: state
        entity_id:
          - input_boolean.test
          - sensor.some_sensor
          - light.kitchen_light
        not_to:
          - unavailable
          - unknown
        not_from:
          - unavailable
          - unknown
    sensor:
      unique_id: dbf841e2-ae6f-4fc1-9534-a1046204945f
      name: Nominal Change History
      state: "OK"
      attributes:
        changes: >
          {% set current = this.attributes.get('changes', {}) %}
          {% set new =
            { trigger.entity_id:
              {
                'datetime': trigger.to_state.last_changed.isoformat(),
                'from': trigger.from_state.state,
                'to': trigger.to_state.state
              }
            }
          %}
          {{ dict(current, **new) }}

How to retrieve the data

Note: Change input_boolean.test to the entity for which you want to retreive the stored data.

To get the date and time of the last change as datetime object:

{{ state_attr('sensor.nominal_change_history', 'changes')['input_boolean.test'].datetime | as_datetime }}

To get the state the entity changed from:

{{ state_attr('sensor.nominal_change_history', 'changes')['input_boolean.test'].from }}

To get the state the entity changed to:

{{ state_attr('sensor.nominal_change_history', 'changes')['input_boolean.test'].to }}

The Home Assistant Cookbook - Index.

2 Likes