Cannot access last_changed value of helper with state()

I’m fairly sure I’ve found a bug in how the state() function works in 2024.1.5/11.4

I’ve read this info (Last_updated State and last-changed in Lovelace) and this similar issue (difference between states and state_attr) as well as hours and hours of troubleshooting with chatGPT, but no luck.

Basically, I have a dozen 3d printers and I want to know if any of them stop drawing power (<20w), but only if they’ve been on for a while. The best way I’ve been able to figure this out is to use helpers and two separate automations - one to “start the clock” when they turn on (for at least 5s) and one to mark them as no longer printing (>5s). If they’ve been heating long enough when they turn off, they send an email, but getting the last_changed state from the helper is proving difficult.

I can retrieve it with:
{{ states.input_boolean.printer_01_printing.last_changed }}

but since I don’t want to set up 12+ automations, I have a formula to determine the helper based on the triggering entity I extract with another focmula, so I have to use:
{{ states('input_boolean.printer_' ~ printer_num ~ '_printing').last_changed }}

but this doesn’t seem to work. Even just plugging in:
{{ states('input_boolean.printer_01_printing').last_changed }}

Does not work (says “‘str object’ has no attribute ‘last_changed’”)

Would love help here, I’m at the end of my rope…

I know there are other possible ways to do this and I’m definitely open to it, but this also seems like a flaw that could/should be fixed if we can confirm I’m not just missing something…

You are missing something. You want:

{{ states['input_boolean.printer_' ~ printer_num ~ '_printing'].last_changed }}

Here are the various types of access:

{{ states.entity_id }}     # is a reference to a State object

{{ states['entity_id'] }}  # is equivalent to that

{{ states('entity_id') }}  # is a function that returns
                           # the string state value of the 
                           # State object

The “dot method” and “bracket method” of accessing objects work the same, but the bracket method is almost always better:

  • allows templating of the entity ID
  • allows for entity IDs that start with a digit
  • allows for “reserved keyword” references like values

SOLVED! Thank you!

For anyone curious, I also solved this by making a ‘datetime’ helper entity and set it to the current time when triggered.

I ended up using both, although redundant, because I got it working first by using a datetime helper entity.

With datetime helpers, I didn’t have an active ‘status’ (although I guess I could have set to a particular time when “off” and used some logic yada yada) but I think the boolean and last_changed state value is the best for this

Thanks again