Why is 'last_changed' causing an error in my template?

I’m trying to use the last_changed of the entity_id that triggers my automation like this:

    trigger:
      - platform: state
        entity_id: 
          - switch.hall_light
          - switch.shed_light
        to: unavailable

    action:
      - service: input_datetime.set_datetime
        target:
          entity_id: >
            input_datetime.time_became_unavailable
        data:
          datetime: >
            {{ states.trigger.entity_id.last_changed }}

but it gives me an error,

Template variable warning: 'None' has no attribute 'last_changed' when rendering '{{ states.trigger.entity_id.last_changed }}'

Why?

For the record:

The trigger variable is already a state object, so there’s no reason to
use states … you can use trigger.to_state.last_changed or just use now()

...
action:
  - service: input_datetime.set_datetime
    target:
      entity_id: 
            - input_datetime.time_became_unavailable
    data:
      datetime: "{{ now() }}"

Yeah, what @Didgeridrew said. And see:

BTW, now() might not be the same as last_changed, since only an attribute might have changed. Oops, I missed there is a “to” specified.

1 Like

Thanks to both of you.

As far as using now()
I was doing that (and it worked well) but I now have a reason to want to use last_changed. The reason is not related to setting a datetime, I used that as simple illustration, but is very specific to my narrow use case but is to do with scripts calling scripts with the possibility of queues forming (thanks @pnbruckner :wink: ).