Today’s sun values

Home Assistant Template

Home assistant holds the next values for various sun events, but it is nice to be able to use today’s value when reporting information. Saving the values from the Sun sensor just after solar midnight will achieve this.

Template Sensor to collect today’s values just after midnight.

# ------------------------------------------------------ Sun Data Sensor
# When next midnight (solar) changes set values for Todays values

- trigger:
   - platform: state
     entity_id: sensor.sun_next_midnight

  sensor:
  - name: Sun States Today
    state: "{{now().date()}}"
    attributes:
      daylight_hours: >
        {{ (state_attr('sun.sun','next_setting') | as_datetime) - (state_attr('sun.sun','next_rising') | as_datetime) }}
      noon:    "{{state_attr('sun.sun','next_noon') | as_datetime }}"   
      sunrise: "{{state_attr('sun.sun','next_rising') | as_datetime }}"
      sunset:  "{{state_attr('sun.sun','next_setting') | as_datetime }}" 
      dawn: "{{state_attr('sun.sun','next_dawn') | as_datetime }}" 
      dusk: "{{state_attr('sun.sun','next_dusk') | as_datetime }}"  
      midnight: "{{state_attr('sun.sun','next_midnight') | as_datetime }}" 

Report the sunrise details

The sun rose, 5 hours ago at 5:00 am and will set in 10 hours at 9:30 pm.

{%- macro sun_times() -%}
{%- from "easy_time.jinja" import easy_time, big_time -%}
{%- set sunrise  = state_attr('sensor.sun_states_today','sunrise') | as_datetime | as_local %}
{%- set sunset  = state_attr('sensor.sun_states_today','sunset') | as_datetime | as_local %}
{% set diff_rose = sunrise < now() %}
{%- set diff_set = sunset < now() %}
{{-('The sun will rise in %s ' | format(big_time(sunrise))) if not diff_rose}}
{{- ('The sun rose %s ago ' | format(easy_time(sunrise))) if  diff_rose}}
{{- 'at ' + sunrise.strftime('%_I:%M %p') + ' and '}} 
{{-('will set in %s' | format(easy_time(sunset))) if not  diff_set}}
{{- ('set %s ago' | format(easy_time(sunset))) if  diff_set}}
{{- ' at ' + sunset.strftime('%_I:%M %p')}}. 
{%- endmacro -%}

{#-
Usage
-#}
{%- from 'tools.jinja' import  sun_times -%}{{sun_times() -}}