I’m trying to consolidate some automations. I have 2 automations that do the same thing but run at different times based on the value of a sensor.
Is it possible to dynamically set a time trigger for an automation?
I’ve tried this
- alias: Good Night Workdays
trigger:
platform: time
at: #'23:00'
{% if is_state('sensor.current_shift','Days') %}
'23:00'
{% else %}
'01:30'
{% endif %}
which results in this error
Error loading /config/configuration.yaml: while scanning for the next token
found character '%' that cannot start any token
in "/config/automations/automations_old.yaml", line 33, column 8
Have 2 triggers and then use conditions to check the other things So any trigger will trigger the automation but then the conditions also need to be met.
As you discovered, the time trigger’s at parameter doesn’t accept a template. Building on the above answers, this should work for you:
- alias: Good Night Workdays
trigger:
- platform: time
at: '23:00'
- platform: time
at: '01:30'
condition:
condition: template
value_template: >
{% set days = is_state('sensor.current_shift', 'Days') %}
{{ days and trigger.now.hour == 23 or
not days and trigger.now.hour == 1 }}
It’s also possible to do this with a single template trigger, but you’d have to enable sensor.time. Then it would look like this:
- alias: Good Night Workdays
trigger:
platform: template
value_template: >
{% if is_state('sensor.current_shift', 'Days') %}
{{ is_state('sensor.time', '23:00') }}
{% else %}
{{ is_state('sensor.time', '01:30') }}
{% endif %}
Working beautifully, I used the time sensor. You are a scholar and a gentleman sir. It always seems so simple once someone else points it out! Thank you muchly.
Thank you - although your suggestion didn’t quite work it did set me down on the right path and made me dig into the docs a little bit. Never a bad thing!
Just an FYI. In an earlier post in this topic I suggested using trigger.now.hour.
Turns out, starting with HA release 0.81 the value of that expression has changed. Prior to 0.81 trigger.now was a timezone aware Python datetime object in the local timezone. Starting with 0.81 trigger.now is a timezone aware Python datetime object in UTC. Therefore, the value you get for trigger.now.hour is not the same with HA version 0.81 and later than it used to be with HA version 0.80 and before (assuming your timezone is not the same as UTC.)
I know I’m resurrecting an ancient thread, but this is what google found me when I was looking for an answer to the same problem today. This is what I ended up with, which to me seems like a simpler answer:
- id: '1641065771514'
alias: Ice On/Off Schedule
description: Turn the ice maker off at night
trigger:
- platform: time
at: 06:00:00
id: 'on'
- platform: time
at: '22:15:00'
id: 'off'
condition: []
action:
- service_template: switch.turn_{{trigger.id}}
target:
entity_id: switch.ice
mode: single