Confused about Sun condition in automations

Hi all,

I am trying to setup a PIR that will activate a light in my hallway but I only want it to do it overnight. I have been trying to use the Sun condition to activate during that time. The example given (Conditions - Home Assistant) says about “when dark” to set:

condition:
  - condition: sun
    after: sunset
    before: sunrise

However if I set that in HA even after the sun has set the condition fails. However if I remove the ‘before’ then, at the very least, it worked after the sun had set and before I went to bed! When I got up (after sunrise) the light is no longer coming on as expected.

I guess my question is, if I just have it set to ‘after: sunset’ will this just work until sunrise? Why doesn’t the example work as suggested from the help docs?

HA versions:

Home Assistant Core 2022.6.7
Home Assistant Supervisor 2022.05.3
Home Assistant OS 8.2

I think the problem is that the condition passes the day boundary, try reversing the logic:

condition:
  condition: not
    conditions:
      - condition: sun
        before: sunset
        after: sunrise

So the condition checks if it’s not between sunrise and sunset and this way it should work.

Cheers! I’ll give this a go later today when the sun sets :slight_smile: (well 2 hours before as I added an offset lol)

Glad if i could help. You mentioned the docs, there is written that you can’t use both of the before and after in an and condition. So you need for the long way an or condition:

condition:
  condition: or
  conditions:
    - condition: sun
      after: sunset
    - condition: sun
      before: sunrise

But the above way should be a line shorter :wink:

Fair point, I missed that part of the text and went straight for the examples :blush:

I butchered the offset times to simulate different times of the day to test and it does indeed seem to work :slight_smile: will report back after tonight!

I just posted this elsewhere, but couldn’t link it. Sorry. Here’s what I do -
This turns on lights based on motion, only turns them on an hour and 45 before sunset, and off at sunrise. You need 2 conditions to run up to midnight, then after midnight.

- id: "16317xxxxxxx"

  alias: Kitchen MotionGroup-light ON 

  description: Kitchen MotionGroup-light ON 

  trigger:

    - platform: state

      entity_id: group.kitchenmotion

      id: group.kitchenmotion

      from: "off"

      to: "on"

  condition:

    - condition: or

      conditions:

        - condition: sun

          after: sunset

          after_offset: -01:45:00

        - condition: sun

          before: sunrise

  action:

    - service: switch.turn_on

      target:

        device_id: 4856f51b9xxxxxxxxxxxxxxxxx

  mode: single

Simply use a State Condition:

condition:
  - condition: state
    entity_id: sun.sun
    state: below_horizon

Hi SandmanXX

That is very similar to what I have ended up with :slight_smile: thanks for the script!