home-assistant / core

:house_with_garden: Open source home automation that puts local control and privacy first.
https://www.home-assistant.io
Apache License 2.0
71.14k stars 29.81k forks source link

time variables interpreted as string #124523

Closed pedolsky closed 2 weeks ago

pedolsky commented 2 weeks ago

The problem

I have a few automations that use time variables, e.g.

a)

uptime: "{{ now() - states('sensor.uptime')|as_datetime|as_local }}"

b)

stopp: |
   {{ today_at((state_attr('automation.dammerungsbeleuchtung', 'last_triggered')|as_local).strftime('%R')) }}

Using these variables as part of a condition results in the following error and the automation will not be executed:

TypeError: '>' not supported between instances of 'str' and 'datetime.timedelta'

Examples: Fails:

    condition:
      - "{{ uptime > timedelta(minutes=2) }}"
    condition:
      - alias: nur tagsüber
        condition: template
        value_template: |
          {{ now() < stopp }}

Works:

    condition:
      - |
        {%- set uptime = now() - states('sensor.uptime') |as_datetime |as_local %}
        {{ uptime > timedelta(minutes=2) }}
    condition:
      - alias: nur tagsüber
        condition: template
        value_template: |
          {{ now() < today_at(stopp) }}

What version of Home Assistant Core has the issue?

core-2024.8.1

What was the last working version of Home Assistant Core?

No response

What type of installation are you running?

Home Assistant Supervised

Integration causing the issue

automation

Link to integration documentation on our website

https://www.home-assistant.io/docs/automation/

Diagnostics information

No response

Example YAML snippet

No response

Anything in the logs that might be useful for us?

No errors in logs!

Additional information

If this is no bug but expected behavior, there should be at least a warning in the logs that the automation failed.

jbouwh commented 2 weeks ago

The output of Templates is always to a string. So you need to do the logic inside of the template.

pedolsky commented 2 weeks ago

Thank you for responding. It would explain why the second example fails.

But why does it make a difference in the first one (uptime)?

jbouwh commented 2 weeks ago

Uptime is calculated, but the result is a s string. In the comparson now results in a date time. So you need to convert to datetime before you can compare.

pedolsky commented 2 weeks ago

So I mistakenly assumed that the variable was interpreted as time. Thank you very much for your efforts, much appreciated!