Automation Trigger Offset from template value ... dynamic trigger offset?

Hi to the community,

I have a question about the offset option of an automation trigger: My plan is to use the sun attribute “next_rising” timestamp to dynamically delay the closing of the cover depending on the month. I.e. in summer the delay should be around 20-40min in winter just a few minutes as the sun sets more rapidly.

As the delay value of the trigger should be in the form of ‘HH:MM:SS’ I made the following templating:

{% if (as_timestamp(states.sun.sun.attributes.next_rising)) | timestamp_custom("%m") == "06"  -%}
  "00:{{ int(2.0 * 1350 / 60)}}:00"
{%- else -%}
  "00:{{ int((1/(int((as_timestamp(states.sun.sun.attributes.next_rising)) | timestamp_custom("%m")) - 6) | abs) * 1350 / 60)}}:00"
{%- endif %}

But I could not insert it as trigger offset (in YAML mode). After copying my text to “offset” it simply disappears. Could someone help me out … but maybe I follow a strange route here and I could not solve my problem with the offset?

… doesn’t support templates.

Ok thanks for the reply! That’s said … a delay can be done with a timer, but a “pre-delay” (i.e. 20 min before sunset?) … Are there any suggestions?

I suggest you use a Template Trigger in your automation.

For example:

alias: example
trigger:
  - platform: template
    value_template: >
      {% set rising = states('sensor.sun_next_rising') | as_datetime | as_local %}
      {{ now().strftime('%H:%M') == (rising - timedelta(minutes=20)).strftime('%H:%M') }}
condition: []
action:
  ... your actions ...

How the template works

This line creates a variable named rising containing the date and time (as local time) represented as a datetime object.

{% set rising = states('sensor.sun_next_rising') | as_datetime | as_local %}

This portion subtracts 20 minutes from rising and converts the result into a time string containing hours and minutes. This is the “offset rising time”.

(rising - timedelta(minutes=20)).strftime('%H:%M')

The last line compares the current time, represented as a time string, to the offset rising time string. It performs this comparison every minute.

      {{ now().strftime('%H:%M') == (rising - timedelta(minutes=20)).strftime('%H:%M') }}

When the current time is equal to the offset rising time, the Template Trigger is triggered.

Thats a very nice approach!

Just one questions: Why it performs this comparison every minute? Is this an internal home assistant timer?

Thanks a lot for you effort!

1 Like

A template is evaluated whenever an entity’s state value changes or if it references certain functions that update themselves periodically.

This template is evaluated whenever the value of sensor.sun_next_rising changes and when the value of now() changes (it updates itself every minute).

1 Like

Ahhh understood!
Thanks a lot for the clarification!