How to calculate daylight hours from sun.sun next_rising and next_setting?

Hello!

How can I calculate the hours of sunlight (daylight) by sun.sun next_rising and sun.sun next_setting?

I created 2 template sensors under helpers:

{{ as_timestamp(state_attr("sun.sun", "next_rising"))|timestamp_custom("%H:%M") }}

Result, e.g.: 08:04

{{ as_timestamp(state_attr("sun.sun", "next_setting"))|timestamp_custom("%H:%M") }}

Result, e.g.: 17:14

As these are strings, I do not understand how I could calculate the hours between these 2 times.

Or should I follow another approach instead of creating the aforementioned 2 template sensors and create 1 template sensor that directly calculates the sunlight/ daylight hours? But how?

Thanks for sharing your thoughts and help! :+1:

Use the as_timedelta filter/function to convert each string to a timedelta object, then just subtract one from the other. You could do it something like this:

{{ as_datetime(state_attr("sun.sun", "next_setting"))
.time() | string | as_timedelta
- as_datetime(state_attr("sun.sun", "next_rising"))
.time() | string | as_timedelta }}

This calculation will have one error though – it will only show the “correct” value in the evening/night, after sunset but before sunrise. At any other time during the day, those times will be fetched from different days (+/- 1 day) so may differ by some minutes.

1 Like

You can have a condition that inverts the subtraction when it’s at night. So when one of those times is later than the other, and vice versa.

1 Like

Or you could use a triggered template sensor and only calculate it some time between midnight and dawn. E,g.

template:
  - trigger: 
      - trigger: time
        at: "01:00"
    state: etc...
1 Like