The states() function returns a string, not a state object.
Generically, the proper way to get an attribute value is by using state_attr("<entity_id>", "<attribute_name>"), but last_modified / last_changed cannot be obtained that way, so your 1st form is the only correct way for those.
Thanks for your help! I’d already found out that the last_changed attribute wasn’t present for this entity, so after searching I stumbled upon the first, working method.
My next question is: WHY can’t this attribute not be accessed in the proper way, using state_attr, since its value is obviously present.
The function I am trying to build is one that checks the last state change of several network devices, so I need to feed it a variable entity_id. But, for the same reasons you gave in your reply, this also won’t work (tried it):
{% set entity = ‘states.binary_sensor.net_network_bsm.last_changed’ %}
{{ as_timestamp(entity) }}
How do I solve this? I see no plausible path for a solution.
Thanks for your very useful help; I see now where things go wrong…
It works indeed, but I guess the only way to make the entity “variable”, i.e. feeding the timestamp function various state objects such as:
Even if it did exist the template would still fail because it’s fundamentally wrong. I see that ChatGPT continues to be a poor reference for Home Assistant, confidently suggesting nonsense.
The states() function returns the value of an entity’s state property and it’s always a string. ChatGPT led you to believe that a string value can have a property like last_changed but it doesn’t.
If the entity’s last_changed property is defined and has a value, either of these will work:
I suggest you review the documentation for State Objects. You’ll see that attributes and last_changed are properties of a State Object. The state_attr() function is designed to work with a State Object’s attributes property (and nothing else).
Great! That works and solves my problem!
While you were thinking up this solution, I’ve challenged ChatGPT to find one too; it came up with a gazillion of other solutions, none of them worked…
So a human is still better than AI…
I didn’t know about this policy; good to know and a very sensible one!
So far, I’ve used ChatGPT to give myself a “head start” in writing code (again); I am a former programmer from the assembler / C++ era. ChatGPT was certainly helpful and already saved me many hours browsing and googling, but I’ve also learned that on many occasions it is totally lost. But as with all information obtained from the Internet, one should always have a critical mind towards it.