update July 2018: I reworked the sensor and made it more precise. The prior version had some glitches when transitioning from dawn to day and from day to dawn (the sensor switched to “night” for a couple of minutes). This new version resolves this problem since it put’s the “day” status to the exit/else condition. Attention: The negative value of the solar angle (-4 in my case) could vary according to your latitude, so you might need to change it to another value.
For those of you who like nice icons in the GUI, I added an icon template. Kudos to @Mariusthvdb who brought up this idea.
- platform: template
sensors:
period_of_day:
friendly_name: 'period of the day'
value_template: >-
{% 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_template: >-
{% 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 %}