Count Hour of Sun

Hi all, i’m tryng to create a sensor that count the hour of sun during the day. I used the history_stats but i had to add in start and end the variable of the sunrise and the sunset because the weather component keey the sunny state even if is night.

Can this work? :

sensor:
  - platform: history_stats
    name: Ore di Sole Oggi
    entity_id: weather.milano
    state: 'sunny'
    type: time
    start: "{{ state_attr('sun.sun', 'next_rising') }}"
    end: "{{ state_attr('sun.sun', 'next_setting') }}"

dont know but i use this

      sunlight:
        value_template: >
          {% set nr = as_timestamp(state_attr('sun.sun','next_rising')) %}
          {% set ns = as_timestamp(state_attr('sun.sun','next_setting')) %}
          {% if nr > ns %}
          {% set nr = nr - 60*60*24 %}
          {% endif %}
          {{ (ns - nr)|timestamp_custom('%H:%M',false) }}

this template sensor take no care of the weather condition or i’m wrong? i can’t see any sun.sun “sunny” states…

correct bro only look at the sunrise and sun set

oh ok. probably i was not clear in my question. I want to know if there is sun during the day… not only the time between sunrise and sunset…

just realized that this can not work because the “next_rising” or “Next_setting” change immediatly to thge next day when the event occurs…
need a way to take this date and do a "-1) on the number of the day… but this can be a problem if the number of the day is 1…

Solved in this way :

#SENSOR GO TRUE IF WEATHER IS SUNNY AND SUN IS ABOVE HORIZON
  - platform: template
    sensors:
      sole_e_alba:
        friendly_name: "Sole e alba"
        value_template: >-
          {{is_state('weather.milano', 'sunny')
            and is_state('sun.sun', 'above_horizon')}}


 
#SENSOR COUNT HOUR OF SUN UP AND SUNNY OF THE PREVIOUS SENSOR
  - platform: history_stats
    name: Ore di Sole Oggi
    entity_id: sensor.sole_e_alba
    state: 'True'
    type: time
    start: '{{ now().replace(hour=0, minute=1, second=0) }}'
    end: '{{ now().replace(hour=23, minute=59, second=0) }}'

1 Like