is there a way to set a maximum time? the actions in the automation may take place at the sunset trigger until it is, for example, 9 pm, then the actions must be carried out anyway
Add 9pm as an additional trigger. If you don’t want the actions run twice, you can check the last trigger time. Here, it checks the automation hasn’t run in the last five hours (18,000s). Change ENTITY_ID for the actual entity ID of your automation.
description: ""
mode: single
trigger:
- platform: sun
event: sunset
offset: "-00:20:00"
- platform: time
at: "21:00"
condition:
- "{{ now()|as_timestamp - state_attr('automation.ENTITY_ID','last_triggered')|as_timestamp(0) > 18000 }}"
action:
...
That will run at 20 mins before sunset or at 9pm, whichever comes first.
@troon has the right answer. but a small tweak on his, i think you can use the “this” object which will make this portable and not need to replace the entity_id.
description: ""
mode: single
trigger:
- platform: sun
event: sunset
offset: "-00:20:00"
- platform: time
at: "21:00"
condition:
- "{{ now()|as_timestamp - this.attributes.last_triggered|as_timestamp(0) > 18000 }}"
action:
...
@Troon, sorry, i’m not clear how it suggests it might not work? i don’t see that in the docs. but maybe i’m missing something.
we need to check for the first run case where last_triggered isn’t set at all?
@tom_l is your code a better way to check if it’s run already? apologies, i’m not following how it would do that. i may be misreading it, but it looks like it’s checking if it was run more than 1 minute ago. or are you just showing a case where you use it yourself?
The docs suggest that this might only be valid at the start of the action block (“at the moment of triggering the actions”), implying it might not be available earlier on in the condition block where we need it. Tom is confident that it is available earlier, so perhaps the docs need clarifying.
That’s what the (0) in the as_timestamp() does. If it can’t convert the attribute to a timestamp, it returns 0, which is definitely more than five hours ago.