Automation Help with Time Conditions (Turn off lights for ##mintues between certain hours)

I just experimented with the automation and discovered something interesting.

I set the time period to be from 20:30 to 21:30.
I set the duration (for:) to 10 minutes.
I turned the light on at 20:28.
The light failed to turn off at 20:38.

At 20:40 I manually turned the light off and then back on.
The light turned off at 20:50.

At 21:00 I turned the light on.
At 21:10 the light turned off.

At 21:25 I turned the light on.
It did not turn off at 21:35 (i.e. past the boundary of the time period).

It would appear that the automation expects to see a state-change from off to on during the time period before it begins counting the duration. If the light is already on before the time period begins, it won’t start counting the duration.

In light of this result, this automation, in its current form, is unlikely to work the way you want.

  1. If group.all_master_bedroom is already on before 22:30 then this automation will never turn it off.
  2. If group.all_master_bedroom is turned on at 02:00 it will not be turned off 45 minutes later, at 02:45, because that’s beyond the time period’s boundary (02:30).

I believe one solution might be to move the condition section into the action section. It doesn’t fix the second issue only the first one. However, it may do it a bit too aggressively. If the group is already on for 45+ minutes before 22:30, it will get immediately turned off at 22:30.

- id: 'master_bedroom_lights_off'
  alias: Master Bedroom Lights Off
  trigger:
    entity_id: group.all_master_bedroom
    platform: state
    from: 'off'
    to: 'on'
    for: '00:45:00'
  action:
    - condition:
        condition: time
        after: '22:30:00'
        before: '02:30:00'
    - service: homeassistant.turn_off
      data:
        entity_id: group.all_master_bedroom