Most recent sunset

In order to access the most recent sunset, I have a slightly convoluted setup populating a sensor on sunset:

alias: Save Most Recent Sunset
triggers:
  - trigger: sun
    event: sunset
actions:
  - action: input_datetime.set_datetime
    data:
      datetime: "{{ now() }}"
    target:
      entity_id: input_datetime.sun_last_setting

Is there a simpler way to access the most recent sunset?

I don’t know if it’s “simpler”, but the Sun2 custom integration has a variety of alternate sun-related sensors which could be used…

template:
  - sensor:
      - name: Most Recent Sunset
        state: |
          {% set (now,ent) = (now(),'sensor.home_sun_setting') %}
          {% set times = [state_attr(ent,'today'), state_attr(ent,'yesterday'), now] | sort %}
          {{ times[times.index(now)-1] }}
        device_class: timestamp

You could use a trigger-based template sensor rather than an automation, which is conceptually slightly simpler as it only needs one entity (the sensor) rather than two (the automation and the helper).

template:
  - trigger:
      - trigger: state
        entity_id: sun.sun
        to: 'below_horizon'
    sensor:
      - name: Most recent sunset
        state: "{{ now() }}"
1 Like