Trying to create a sensor to represent a 10 minute offset to sunrise

I am trying to create a simple sensor in my templates.yaml file to represent an offset of +10 minutes to the time of sunrise. This sensor will be used on an entity card on my dashboard.
The following code works to correctly provide the time of sunrise (without an offset):

- sensor:
  - name: "Sunrise_with_offset"
    state: "{{state_attr('sun.sun', 'next_rising') | as_datetime | as_timestamp | timestamp_custom('%-I:%M %p')}}"

As an example, it returns 6:41 AM. However, if I attempt to add a ten minute offset as follows, the sensor changes to unavailable rather than returning 6:51 AM:

- sensor:
  - name: "Sunrise_with_offset"
    state: "{{state_attr('sun.sun', 'next_rising') | as_datetime + timedelta(minutes=10) | as_timestamp | timestamp_custom('%-I:%M %p')}}"

Maybe I’m just not firing on all brain cylinders this morning, but I am just not seeing why this offset addition breaks the code.

Any insight would be greatly appreciated. Best regards.

There’s no need to convert it to a timestamp before converting it to a string, but you do need to use () around the summation. Otherwise, the conversion to a string is applied to just the timedelta() which causes an error.

- sensor:
  - name: "Sunrise_with_offset"
    state: >
      {{ (state_attr('sun.sun', 'next_rising') | as_datetime | as_local 
      + timedelta(minutes=10)).strftime('%-I:%M %p')}}
- sensor:
  - name: "Sunrise_with_offset"
    state: "{{ (state_attr('sun.sun', 'next_rising')|as_timestamp+600)|timestamp_custom('%-I:%M %p') }}"

Thanks! The HA community is the BEST!

1 Like

This code depends on sun.sun changing state (the developer tools show this as dependency). As the sun moves during the day, it is supposed to be always changing and therefore firing an event every minute.

The sunrise/sunset for today only changes once a day, on day change. Being dependant on sun.sun seems to make no sense here. It may make sense to create a trigger base template sensor and to define a trigger on day change to update the sunrise/sunset for today, but this is only to avoid the wrong trigger management for the sunrise/sunset attribute of the sun.sun component.

Right?

(I’d love to be wrong, please tell me that I’m missing something, everything is fine and only once a day the calculation is being triggered)

Your not completely wrong, but the “right” answer depends on the use case and the needs of the user. OP wanted to display the time with an offset and they stated that the Sun integration’s “next rising” attribute was accurate for their purposes.

The answers above will vary in accuracy because the source sensor is not “today’s sunrise” it is the next sunrise. The attribute value rolls over right after sunrise. That means the value throughout most of the day is for tomorrow. The difference between sunrise today and tomorrow changes throughout the year dependent on latitude, so the answers above might not be accurate enough for some uses.

Using trigger-based template sensors to create “today’s rising” or similar sensors would be one option for more accurate times. Another great option is the Sun2 custom integration since it includes multiple dawn and dusk sensors that don’t roll over on the event and attributes for yesterday’s and tomorrow’s events.

Thank you for the hint that sunrise is the next sunrise, not the sunrise of today. I wasn’t aware of that. But that wasn’t my question.

My point was that the calculation is being done every minute as shown in the options of the template sensor entity. It only can change if sun rise changes, so the is once per day. Not once per minute. But the trigger for the recalculation is fired every minute. In the developer tools the dependency of state_attr(“sun.sun”, “next_rising”) is shown as sun.sun. For sun.sun it makes sense to fire every minute, as the sun does not stop moving (ok: the earth moves, the sun position changes, but you know what I mean).

Shorter: Value depends on sun rise. Event depends on sun.sun. This is wrong, the event should like the value depend on sun rise change and not fire every minute. Right? You say this behaviour is better for sun2?

Here’s what I see:

This template listens for the following state changed events:

Entity: sun.sun

The template will be evaluated when a state-change is detected. My understanding is that when the value of the sun entity’s attribute changes (next_rising) this is what causes the template to be updated.

Template integration - Rate Limiting Updates

1 Like

OK. State change is only sun is up, sun is down. And on value change of the attribute also an event is triggered, so it is calculated 3 times a day. Fine! Thank you.

I’m sorry, but I don’t understand the point you are trying to make.

Keep in mind that this thread is over a year old and changes have been made to the Sun integration since it was marked as solved. Currently, the sun integration creates it’s own sensor for next rising and next setting. So, if your concern is that basing the template on the attribute of sun.sun is somehow making the template render more than necessary, simply change the template to use sensor.sun_next_rising.

As I stated previously, you can use a trigger-based template sensor to control when the template is rendered. Just make sure that you take into account the possibility of one or more triggering failing if anything important will be dependent on the accuracy of the sensor’s value.

The sensor which was asked in the question seems to implement exactly the same thing I am doing, that’s why I replied to the old thread, because it is the question which I wanted to know an additional detail.

What I am doing:

The covers in the ground floor shall open 5 minutes before sunrise, but not before eg 6 in in workdays and 8 on weekends and holidays.

So I have some helper input.datetime which are input fields at the settings dashboard
Rolladen_auf_Feiertag
Rolladen_auf_Werktag
Rolladen_zu_max

There are two template sensors

Rolladen_auf_Heute

{{  today_at(max(states('input_datetime.rolladen_auf_werktag') 
             if is_state('binary_sensor.workday_sensor','on')
             else states('input_datetime.rolladen_auf_feiertag')
     , as_timestamp(as_datetime(state_attr("sun.sun", "next_rising"))-timedelta(minutes=5)
     ) | timestamp_custom('%H:%M:%S')
   ))
  }}

Rolladen_zu_heute

{{  today_at(min(states('input_datetime.rolladen_zu_max')
     , (as_timestamp(as_datetime(state_attr("sun.sun", "next_setting"))+timedelta(minutes=5)
     ) ) | timestamp_custom('%H:%M:%S')
   ))
  }}

which are shown on the settings dashboard as information.

The covers are being controlled by a state machine.

Values for Rolladen.Zustand (also editable on that settings dashboard):
Manuell
Auto.Morgensonne
Auto.Mittagssonne
Auto.Tag
Auto.Nacht

The automation “Auto Rolladen Nacht Ende” for instance is triggered by the time Rolladen_auf_heute if state machine is not in state Manuell. It activates the scenes for the covers depending on the weather forecast (cloud and teperature) and sets the state to Auto.Morgensonne or Auto.Tag (depending on the forecast result). And so on.

I documented the state machine in a DrawIo picture, but it is only for myself and maybe my family.

And what made me think about when the events get triggered was the sensor for workday/holiday malfunctioning yesterday … so my whole question here was: How often is that template sensor being recalculated? Was the answer given last year fine or does it do unnecessary operations? And as sun.sun state change is only 2 times a day (sun up or sun down) and an event also occurs on value change of the attribute, I’m fine with the answer.
(am still searching the cause for that workday sensor problem, but that would be another topic - edit: something was broken, am not the only one, see here)

Your template uses today_at() so it will be updated at least every minute.

From the Templating documentation:
image

2 Likes