Help with automation using sun & time conditions, crossing midnight

I’ve been using Home Assistant for a couple of months now, and love it. I’ve written several automations, but I need some help with this one. I’ve been puzzling over this, looking at all kinds of automation examples with time and sunset, and I can’t figure out how to make this work. I want to turn a light on when a motion detector triggers, but only between sunset and 10pm. This is where I am so far:

- alias: Turn on light when motion between sunset and 10pm
    platform: state
    entity_id: sensor.motion_sensor
    to: 'motion detected'
    condition: and
    - condition: state
      entity_id: sun.sun
      state: 'below_horizon'
    - condition: time
      before: '22:00:00'
    service: light.turn_on
    entity_id: light.my_light
      brightness: 120

It partially works…The problem is that after midnight, when the day changes, the conditions become true again (until sunrise). I do not want the light to turn on between midnight and sunrise. I’m probably missing something obvious, but if someone could help I’d really appreciate it. Thanks in advance!

It’s somewhat of a dirty solution but will work. Just update your code like this.

- condition: time
  before: '22:00:00'
  after: '12:00:00' 

You can make the after time anything bigger than the maximum sunrise time but lower than minimum sunset time at your location .

1 Like

Thank you very much! I never though of doing it this way. I’ll try it out!

You should also be able to change the condition to something like below. I have not tested this so I don’t know for sure if it is the exact syntax.

  - condition: or
      - condition: time
        before: '22:00:00'
      - condition: sun
        after: sunset