Automations with dusk, dawn, night and day period

Has the way you implement this component changed in 2023?
I added the ‘sensor: - platform template…’ section to my configuration.yaml but it didn’t show up as an Entity after a restart of the yaml configurations.

Is anyone still using this template code? It stopped working for me beginning of this week.
In fact it skips dawn since April 30th. I am not good in templating code. Hopefully somone can verify why its not working.
Here is the code which worked for me for at least a year:

- name: period_of_day
        state: >-
          {% if (as_timestamp(states.sun.sun.attributes.next_dusk)) - (as_timestamp(states.sun.sun.attributes.next_setting)) < 0 %}
            dusk
          {% elif (as_timestamp(states.sun.sun.attributes.next_rising)) - (as_timestamp(states.sun.sun.attributes.next_dawn)) < 0 %}
            dawn
          {% elif (states.sun.sun.attributes.elevation) < -4 %}
            night
          {% else %}
            day
          {% endif %}
        icon: >-
          {% if (as_timestamp(states.sun.sun.attributes.next_dusk)) - (as_timestamp(states.sun.sun.attributes.next_setting)) < 0 %}
            mdi:weather-sunset-down
          {% elif (as_timestamp(states.sun.sun.attributes.next_rising)) - (as_timestamp(states.sun.sun.attributes.next_dawn)) < 0 %}
            mdi:weather-sunset-up
          {% elif (states.sun.sun.attributes.elevation) < -4 %}
            mdi:weather-night
          {% else %}
            mdi:weather-sunny
          {% endif %}

Thanks for help!

Hi Till!

This code snippet has been updated over time and now it looks like below. It is working fine in my environment.

- platform: template
    sensors:
      period_of_day:
        friendly_name: 'period of the day'
        value_template: >-
          {% set elevation = state_attr('sun.sun', 'elevation') %}
          {% set rising = state_attr('sun.sun', 'rising') %}
            {%- if elevation <= -8 -%}
            night
            {%- elif -8 < elevation <= -4 -%}
            {{ 'dawn' if rising else 'dusk' }}
            {%- else -%}
            day
            {%- endif -%}
2 Likes