Automation Last Triggered

You’re welcome!


Interesting you should say that because when I originally tried it, it failed.

2023-03-30 07:46:59.084 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: ‘this’ is undefined when rendering ‘{{ now() - this.attributes.last_triggered | default(as_datetime(0)) < timedelta(minutes=1) }}’

Building off your answer, here’s how to use default() to solve the problem of the automation not having ever been run:

This will return true if the automation hasn’t ever run or has been run in the last 12 hours

{{ now() - state_attr('automation.night_time', 'last_triggered') | default(now(), true) < timedelta(hours=12) }}

if state_attr('automation.night_time', 'last_triggered') is none it will return the default value, which is now() and now()-now() is less than 12 hours.


My use case was that I didn’t want the automation to run if it had already run in the last 6 hours:

{{ now() - state_attr('automation.weather_warnings_check', 'last_triggered') | default( as_datetime('0'), true) > timedelta(hours=6) }}

In this case, default is as_datetime('0')
Which returns:
1970-01-01 00:00:00+00:00

And now() - 54 years ago is greater than 6 hours.


For default() Passing in true as the second parameter will return the default value if the value is defined but blank.

A year ago, I linked to an example of how to use default (it’s in the post you replied to).