Using variables in automations with templates

Hi all,
I have an automation, where I use two different times and a template where these times are being used.

alias: 40 - Test switch On Off at preset times
trigger:
  - platform: time
    at:
      - "20:10:00"
      - "20:40:00"
  - platform: homeassistant
    event: start
action:
  - service: >-
      switch.turn_{{ iif( (20,10) <= (now().hour, now().minute) < (20,40), 'on'
      , 'off') }}
    target:
      entity_id: switch.wcd_lidl_3

How can I use variables for both time values, so when i change the time at trigger: it also changes the times in the Template

If you want to change them from the frontend create and use two input datetime helpers with time only.

trigger:
  - platform: time
    at: 
      - input_datetime.one
      - input_datetime.two
  - platform: homeassistant
    event: start
action:
  - service: >-
      switch.turn_{{ iif( today_at(states('input_datetime.one')) <= now() < today_at(states('input_datetime.two')), 'on'
      , 'off') }}
    target:
      entity_id: switch.wcd_lidl_3

Thank you @tom_l . Ok, that looks not to hard to do.
But what if I do not want to use the frontend, but want to set the times in the automation itself, to put the time value in the helper? Is there a way to do that?

Sure. You have to reload automations every time you change the times though:

variables:
  time_1: "20:10:00"
  time_2: "20:40:00"
trigger:
  - platform: time
    at: 
      - time_1
      - time_2
  - platform: homeassistant
    event: start
action:
  - service: >
      switch.turn_{{ iif( today_at(time_1) <= now() < today_at(time_2), 'on'
      , 'off') }}
    target:
      entity_id: switch.wcd_lidl_3
1 Like

Ah, great, did not know the use of variables within the automation… Have to learn a lot. I will try both options. And yes, perhaps the frontend version is a better choice.
Found a tutorial about the use of frontend with helpers:
How To Use HELPERS In Home Assistant - TUTORIAL
Thank you!

Sorry I misread your post. The variables are local to that automation only.

You can use the input_datetime.set_datetime service to set the times in another automation if using my first example.

https://www.home-assistant.io/integrations/input_datetime/#input_datetimeset_datetime

Hi @tom_l I am sorry, i deleted my entry because i want to test something else fist…