Getting a template value with a string variable representing an entity name

In the template below, A returns a timestamp as expected. How can I create a template that uses a variable that will return the same value?


{% set UC = 'sensor.be469zp_connect_smart_deadbolt_user_code' %}
A  {{ states.sensor.be469zp_connect_smart_deadbolt_user_code.last_changed }}

B  {{ states.sensor.<<UC>>last_changed }}


{% set UC = 'sensor.be469zp_connect_smart_deadbolt_user_code' %}
A  {{ states.sensor.be469zp_connect_smart_deadbolt_user_code.last_changed }}

B  {{ states.sensor[UC].last_changed }}
1 Like

close but need to remove sensor from the string

{% set UC = 'sensor.be469zp_connect_smart_deadbolt_user_code' %}
{{ states.sensor[UC.split('.')[-1]].last_changed }}

or

{% set UC = 'sensor.be469zp_connect_smart_deadbolt_user_code' %}
{% set domain, object_id = UC.split('.') %}
{{ states[domain][object_id].last_changed }}
1 Like

close but need to remove sensor from the string

Ah, sorry. Missed that.
Unless it is used for something else, I would do

{% set UC = 'be469zp_connect_smart_deadbolt_user_code' %}
{{ states.sensor[UC].last_changed }}

(removing “sensor.” from the value of the “UC” variable)

To get the state and attributes of the sensor you can then also do

{{ states('sensor.' ~ UC) }}
{{ state_attrs('sensor.' ~ UC, 'attribute_foo') }}

This isn’t a wth. Moved.