Device tracker and dynamic last updated

I’m trying to create a template for speech output that uses a variable to get the relative time since the user’s status changed.

The template below works fine, but it’s not dynamic.

{% if is_state("device_tracker.beth", "home") %}
    Beth is home
{%-else -%}
    Beth left {{relative_time(states.device_tracker.beth.last_updated))}} ago
{%-endif%}

I can dynamically check the status of someone with

{% set user = "beth" %}
{% if is_state("device_tracker." + user, "home") %}

but I can’t figure out how to then dynamically get the last_updated variable and pass it into the relative_time function

Found another post that inadvertently solved my issue. Turns out you can use variables in the device_tracker map to get it

{% if is_state("device_tracker." + user, "home") %}
    {{user}} is home
{%-else -%}
    {{user}} left {{relative_time(states.device_tracker[user].last_updated)}} ago
{%-endif%}

you should probably build some safety into this, last_updated may not always exist.

if states.device_tracker[user].last_updated is defined
1 Like