How to switch a light on an off at a given time (atomic actions, or state enforcement)?

I would like to switch on a light at sunset and off at midnight. In other words - so that it is on during this period, except if someone switches it off manually.

I know how to switch it on:

- id: 'lumieres_salon_nuit'
  trigger:
  - event: sunset
    platform: sun
  condition: []
  action:
  - service: homeassistant.turn_on
    data:
      entity_id: light.salon

I have doubts with the off part. The documentation states that

The time condition can test if it is after a specified time, before a specified time or if it is a certain day of the week

I would like to make the action when the time arrives (so at 00:00), not after. Specifically, I do not want the light to be switched off all the time after midnight:

  • if it is on at midnight, I want it to go off
  • if I switch it back after midnight, I do not want the automation to switch it off again, just because it is after midnight.

My question is how to correctly describe these two different states:

  • ensure that the light is on, no matter what, between sunset and midnight (= if someone switches it off, switch it back on immediately)
  • ensure that the light will be switched on at sunset, then switched off at midnight (and nothing else, just these two atomic actions)

It just triggers at the time. Here is a mockup from one of my automations.

- id: 'nnnn'
  alias: name here
  trigger:
  - at: '00:00:00' 
    platform: time
  condition: []
  action:
  - data:
      entity_id: light.salon
    service: light.turn_off

I hope this helps.

- id: 'lumieres_salon_on_sunset'
  trigger:
  - event: sunset
    platform: sun
  condition: []
  action:
  - service: light.turn_on
    entity_id: light.salon

- id: 'lumieres_salon_off'
  trigger:
  - platform: time
    at: '00:00:00'
  condition: []
  action:
  - service: light.turn_off
    entity_id: light.salon

- id: 'lumieres_salon_back_on'
  trigger:
  -platform: state
    entity_id: light.salon
    to: 'off'
  condition: 
  - condition: sun
    after: sunset
  - condition: time
    before: '23:59:59'
  action:
  - service: light.turn_on
    entity_id: light.salon

I used 23:59:59 in the last one because I’m not sure if it would work correctly using 00:00:00. And one second early is probably close enough :slightly_smiling_face: