Using a template condition for historical state

Trying to automate security alarm, for which I need to test historical state of the door, specifically need to know if the door had last changed state more than 5 minutes ago.

This is the template I use:

{{ utcnow()|as_timestamp -
states.binary_sensor.door.last_changed|as_timestamp > 300 }}

It works fine in Developer tools / Template, but not in an actual automation - the Condition test doesn’t pass when testing in Automation editor.

Moreover, when I change the sign from ‘>’ to ‘<’ effectively negating the expression, the template doesn’t pass anyway.

What may I be doing wrong?

Post the automation so we can see how the pieces fit together.

Automation is quite complex, spanning couple of screens in YAML. I’m testing only this particular condition, which always does not pass:

  - condition: template
    value_template: '{{ utcnow()|as_timestamp - states.binary_sensor.door.last_changed|as_timestamp
      > 300 }}'

Copy-paste the following template into the Template Editor (Developer tools → Template) and let us know the three values it reports.

{{ states.binary_sensor.door.last_changed }}
{{ now() - states.binary_sensor.door.last_changed }}
{{ now() - states.binary_sensor.door.last_changed > timedelta(minutes=5) }}

NOTE

  • The first line reports the date and time of door’s last state-change.
  • The second line reports how long ago the state-change occured (in HH:MM:SS format).
  • The third line reports true if the state-change occured more than 5 minutes ago. Otherwise it reports false.

Theses three results will help us understand what is happening with your condition. FWIW, the third line is what I recommend you use in your Template Condition.

2025-05-21 13:25:01.251659+00:00
0:09:59.230401
True

The results suggest this should work correctly:

  - condition: template
    value_template: "{{ now() - states.binary_sensor.door.last_changed > timedelta(minutes=5) }}"