Get time of when a sensor was last changed?

I want to know when a binary sensor was last changed (from on to off or vice versa).
I tried finding information on here but could not find anything that seem to work?

Tested this but it gives me “unknown” as output:

{{ states('binary_sensor.pump_room_dehumidifier_power_on_state.last_changed') }}

Basically I want this value:

OK I solved it through help elsewhere.

For others finding this, you need to use the state object:

{{ states.binary_sensor.pump_room_dehumidifier_power_on_state.last_changed }}
1 Like

last_changed is a property of the entity’s State Object. That’s why you can’t reference its value using states() or state_attr(). In addition, the states() function only accepts an entity_id (and nothing else).

1 Like

Thanks for clarifying! :slight_smile:

I get “Unknown error” when trying to submit the state template below. I want a timer to start when the door is closed (ignoring if open for 5 second or less).
Does anyone know what the error is?
Possibly there is a more elegant method!

{% set entity = states.sensor.eta_192_168_4_103_logs1_inputs_insulation_door %}
{% if entity.state == 'closed' %}
  {% set elapsed_minutes = ((now() - entity.last_changed).total_seconds() // 60) | int %}
  {% set hours = elapsed_minutes // 60 %}
  {{ '%d:%02d' | format(hours, elapsed_minutes % 60) }}
{% elif entity.state == 'open' and (now() - entity.last_changed).total_seconds() > 5 %}
  0:00
{% else %}
  0:00
{% endif %}