Help with value template not working

This template basically checks a light and if it’s been turned off within the last 4 hours. This template works fine testing under dev tools, but never returns a true verdict when inside an automation value template, even when it’s been more than 14400 seconds. What am I doing wrong?


- condition: template
  value_template: >
    {% set last_off = states('input_datetime.last_manual_light_off') %}
    {% if last_off == 'unknown' %}
      true
    {% else %}
      {{ (now() - as_local(as_datetime(last_off))).total_seconds() > 14400 }}
    {% endif %}

Try this version.

- condition: template
  value_template: >
    {% set last_off = states('input_datetime.last_manual_light_off') %}
    {{ last_off == 'unknown' or
      now() - last_off | as_datetime | as_local > timedelta(hours=4) }} 

Really strange same behavior when I change the time to 1 hour. you can see it passes in dev tools, but returns did not pass in the actual automation?


The Template Condition I posted was intended to be placed within an automation’s YAML code. That’s why it has indentation and a leading hyphen (and mimics your original example).

You appear to have placed it into the UI’s editing window for a Template Condition. In that situation, there should be no leading hyphen or indentation of its keys. In fact, it should only be the template itself and no YAML at all.

{% set last_off = states('input_datetime.last_manual_light_off') %}
{{ last_off == 'unknown' or
      now() - last_off | as_datetime | as_local > timedelta(hours=1) }}

Look at your screenshot and you’ll see the field’s name is “Value template”. Therefore the only thing it expects in that field is a Jinja2 template (and not any YAML).

so I open the automation, click on edit in YAML. This is what I get pasting the code above. Apologies if I’m being dense. this is new for me.

Nevermind, pasted the code directly like above without going into yaml editor. I don’t completely understand, but it’s working now. thank you.

1 Like

Now that you have used the UI to create a valid Template Condition, switch the Automation Editor to YAML mode and observe how it translates the UI-based Template Condition into a YAML-based Template Condition. It will look very much like what I originally posted.

The takeaway here is that when you create a Template Condition via the UI, the “Value template” field expects to receive just the Jinja2 template. It knows how to automatically include all the YAML parts. If you add YAML in that field, the end result is an invalid Template Condition.