Trying to access last_changed or last_triggered

hi all,

I am trying to create some variables in templates, but am struggling to get the ‘last_changed’ or ‘last_triggered’ values/timestamps from my Motion Sensors

From this image below the secondary info does show ‘Last_change’ as a selectable dropdown and does give me the last_changes value - i.e. 7 secs ago, 3 hrs ago etc.

However, when I look up the binary sensor, the attributes results do not show any time or last changd etc.

Can anyone share what I am missing and where I should seek to find this/these time values

Many thanks

last_changed and last_updated are properties of the State object:

{{ states['binary_sensor.alarm_master_motion_144']['last_changed'] }}

last_triggered is a normal attribute of an automation entity:

{{ state_attr('automation.ID','last_triggered') }}
1 Like

Thanks Troon - very helpful.

Can you help to advise how:

  1. How I can express this as a simple timestamp? i.e. show 04:49AM instead of default 2024-02-05 04:49:08.953945+00:00 output

  2. and alternatively how do express this as ‘time ago’ - as in 5 secs ago, 2 hrs ago, days etc…

Many thanks

The options are all on the Templating page.

{{ states['binary_sensor.5e_alarm'].last_changed | as_timestamp | timestamp_custom('%I:%M%p') }}
{{ states['binary_sensor.5e_alarm'].last_changed | relative_time }} ago

Alternatives:

{{ states.binary_sensor.alarm_master_motion_144.last_updated.astimezone().strftime('%I:%M%p') }}

If you want more control over the time’s format than what is offered by relative_time, refer to petro’s Easy Time macros.

thanks @123 and @michaelblight - very helpful and will take a look at the docs.

cheers