Simple Time calculation for Sunset (Solved)

Just joined the community.
I have been searching community for simple detecting sunset and Sunrise (Not Dusk or Dawn).
I have seen lots of codes provided from using below and above horizon to Sunset and Sunrise event of sun and elevation and azimuth. And they did not work for me. I wanted to get exact sunset and sunrise bases on its time. I see SUN entity has such attribute and I am trying to use that for my automation.
I have a toggle Helper where I like to set it to on when it is Sunset and off when it is Sunrise. This Helper will be used by several automations in my home assistant…
So far I have created the following template value by using the next_setting attribute of sun entity.

{{ (as_timestamp(states.sun.sun.attributes.next_setting) - 120*60) |float| timestamp_custom('%I:%M %p')}}

However, the result is not local time. I tired to use timepstamp_local filter before float and it did not work. I tried to use as_local() in replace of as_timestamp and that did not work. If I use the following code I get the correct time

{{ (states.sun.sun.attributes.next_setting |float| timestamp_custom('%I:%M %p')}}

But then I cannot use the time to calculate the offset.

So here is what I am trying to do in a nutshell:

  • If current local time is equal to Sun next_setting attribute + offset then
    call service to turn the Helper on
  • if the current local time is equal to Sun Next_rising + offiset then
    call service to turn the Helper off

I also like to know what entity can I use for trigger.

I really appreciate your help in advance…

Why can’t you use the sun trigger? You can add an offset (positive or negative) to event: sunset.

Here’s a start to a little automation I use. It has an offset of 10 minutes before “official sunset”:

- id: 'sunset'
  alias: 'Sunset'
  initial_state: true
  - event: sunset
    offset: '-00:10:00'
    platform: sun
  condition: []
  ... (your stuff-to-do follows here)

Thank you for you reply. This is the code that I had before and it never triggered. I changed the mode from single to queued and no difference.

alias: SuneSetOnOFF
description: ''
  - platform: sun
    event: sunrise
    id: Sunrise
    offset: '+01:00:00'
  - platform: sun
    event: sunset
    id: Sunset
    offset: '-00:30:00'
condition: []
  - choose:
      - conditions:
          - condition: trigger
            id: Sunrise
          - service: input_boolean.turn_off
              entity_id: input_boolean.itissunset
      - conditions:
          - condition: trigger
            id: Sunset
          - service: input_boolean.turn_on
              entity_id: input_boolean.itissunset
    default: []
mode: queued
max: 10

I think you are going to have to split that into 2 automations. One for sunrise, one for sunset.

The interesting thing is that as soon as I enabled the code that I had again, it run at 10:45 am today. It chosen path 2 and turned on the Helper.

So, the trigger started and action was taken but at a wrong time. I checked the time zone in configuration and it is set correctly. What I do not understand is the time stored in sun.attributes. It does not make sense to me.
Here is the Sun attributes information on my system

Okay… really off the wall here but… when you drop down to root on your HA server and enter “date” at the command prompt… do you get an accurate local date and time?

Good call,
The date and time is correct

Does it have to be helper?

Why not create a Template Binary Sensor that is on when the time is between setting+offset and rising+offset, otherwise it’s off.

Hi Tara,
Thank you for your suggestion. I found out that the Sun attributes times are not correct. So, even template would not help when I pull in the Sun next setting attribute value. I am going to search to see if anyone else had issue with SUN attributes value. If I fix the issue, then I think my current automation will take care of it.

Take a look at this, it has sunset according to your location

Then the clock and or timezone is not configured correctly on your system or you live north of the Arctic Circle or the elevation option is incorrect. In other words, something isn’t set correctly because the sun integration normally reports accurate values.

Me thinks 123 is on to something. You should have something like this in your configuration file: Your numbers will vary. I got mine from doing a Google Earth on my home:

  latitude: 30.009163
  longitude: -97.171807
  elevation: 113

Copy-paste this into the Template Editor and confirm each line reports the correct time information:

{{ utcnow() }}
{{ now() }}
{{ utcnow().astimezone() }}
{{ now().astimezone() }}
{{ utcnow().tzinfo }}
{{ now().tzinfo }}
{{ now().astimezone().tzinfo }}

Hi Taras,
Thanks for your reply. I thought you are on to something with elevation value. The configuration section had an elevation = 0 so, I changed it to elevation of my location. However, it did not change the sunset attributes values.
here is the result from template code you ask me. It seems right to me.


and here is the sunset attributes values.

There are 7 hours difference between UTC and Local time and I don’t think these times are in UTC. IF I subtract 7 hours from Dusk time it would 3:55 pm and Dusk in our place happens at 5:55 pm. if I subtract 6 hours that is close.
If we fix the attributes time then we should be ok to use Sunset and Sunrise trigger.

Your time zone is set to America/New_York which is 5 hours less than UTC (even says so in the template results you posted above, -05:00, which is UTC minus five hours). So why do you believe there should be 7 hours difference?

If the time where you live is actually UTC-07:00 then you have selected the wrong time zone.

1 Like

Sorry my bad. You are right, it is 5 hours difference. So, we are back to square one. We know the trigger runs on UTC time for SUN attributes. Only option is to create a template to convert those attributes to local time and then added to trigger of automation.
I need a template to convert the attributes value to local time and apply offset in format of hh:mm and compare it with current time. If it is match then true and if not is then false

I think I got the template. By the way this my first template so go easy on me.

here is the code:

{{ as_timestamp(now())| float | timestamp_custom("%I:%M %p")}} 
{{((as_timestamp(states.sun.sun.attributes.next_setting) - 300 | float))  | timestamp_custom("%I:%M %p")}} 
{% set clt = as_timestamp(now())| float | timestamp_custom("%I:%M %p")%}
{% set sst = ((as_timestamp(states.sun.sun.attributes.next_setting) - 300 | float))  | timestamp_custom("%I:%M %p")%}
{{ clt == sst}}

I will remove the first two lines in my automation. I just added for testing.

I still think a Template Binary Sensor is ideal for your requirements but here’s how to do it the way you want.

Create two Trigger-based Template Sensors that compute offset Sunrise and Sunset times:

  - trigger:
      - platform: time
        at: '00:00:00'
      - platform: event
        event_type: event_template_reloaded
      - platform: homeassistant
        event: start
      - name: 'Sunrise Offset'
        unique_id: 'sensor_sunrise_offset'
        state: "{{ state_attr('sun.sun', 'next_rising') | as_datetime + timedelta(minutes=300) }}"
        device_class: timestamp
      - name: 'Sunset Offset'
        unique_id: 'sensor_sunset_offset'
        state: "{{ state_attr('sun.sun', 'next_setting') | as_datetime + timedelta(minutes=300) }}"
        device_class: timestamp

The two sensors are updated at the start of every day (midnight) and whenever Home Assistant is restarted or Template Entities are reloaded. I set the offset to +300 minutes but change it to whatever you require.

Create an automation that is triggered by the two sensors. The offset sunset sensor turns the input_boolean on and the offset sunrise sensor turns it off. Change the name of the input_boolean to whatever you require.

alias: example sunrise offset
- id: 'on'
  platform: time
  at: sensor.sunset_offset
- id: 'off'
  platform: time
  at: sensor.sunrise_offset
condition: []
- service: "input_boolean.turn_{{ }}"
    entity_id: input_boolean.whatever

Thank you Taras.
All set. Template has been added to config and automation has been created. Let’s see if it triggers at the sunset. Finger crossed!