Simple Time calculation for Sunset (Solved)

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.

image

and here is the sunset attributes values.
image

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.

1 Like

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:

template:
  - trigger:
      - platform: time
        at: '00:00:00'
      - platform: event
        event_type: event_template_reloaded
      - platform: homeassistant
        event: start
    sensor:
      - 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: []
action:
- service: "input_boolean.turn_{{ trigger.id }}"
  target:
    entity_id: input_boolean.whatever
3 Likes

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!

The trigger did not work. when I test the sensor for sunset, this is what I get

Should not we subtract the timedelta?

Add or subtract, that’s your choice. Originally you said you wanted to add the offset so that’s how I composed it.

How much negative/positive offset do you want for sunrise and sunset times?

in my original, I was thing of converting the time to local first then adding the offset butt in your formula you included the offset and conversion of time in on operation. So I just used subtraction and now the offsets are correct. Will see if the trigger happen on sunrise.
The funny thing is that I was looking at the Logbook and I saw this entry:

image

The time is sport on. And when I click on entry SUN, it shows this:

image

All times are in EST time. However in Automation it does not execute on the right time.

All I can tell you is that I have several automations that are triggered based on sunset and I also live in the Eastern time zone and all the automations trigger at the correct time.

The example I posted above is based on another example I provided for another user who needed the offset to be random (as opposed to fixed) every day. It worked for that user.

The UTC datetime shown in your screenshot, 2022-01-28T03:23:28+00:00 is 2022-01-27 22:23:28-05:00 in your local time (EST). Basically that’s today’s sunset time plus 5 hours (300 minutes) to produce 22:23 (EST). It’s currently 18:58 (EST) so it’s obvious why the automation hasn’t triggered yet.

If you want me to continue helping you, I need the information I requested in my previous post.

Thanks Taras. Let’s forget about the offset. Let say we use the actual sunrise or sunset time.

Here is the value of SunriseOffset sensor we created in my system

image

This is the trigger for the Sunrise

-id: 'off'
  platform: time
  at: sensor.sunrise_offset

However, instead of trigger gets executed at 7:36 am, it was executed at 2:36 AM

Why HA shows one time outside of trigger and different time inside trigger for the same sensor?

Did you set elevation properly for your HA location?

IIRC, elevation will wildly change the sunrise sunset. Lat/lon will change your times by about an hour in relation to your position in your Timezone.

Without all those set properly, your sunset/sunrise will be wrong

also keep in mind that elevation is in meters not feet. so… did you put feet in as meters?

This UTC time:
2022-01-28T07:36:34+00:00
is the same as:
2022-01-28T02:36:34-05:00

In other words, 7:36 UTC is 2:36 EST and the trace shows the automation successfully triggered at the scheduled time.

Except the automation is being triggered by sensor.sunrise_offset. According to your screenshot, that sensor is not reporting today’s actual sunrise time. Post the sensor’s current configuration.

I have correct elevation stated in meter in HA.

Sorry Taras,
I am confused. Are you saying that the SunriseOffset is in UTC time and not EST? The whole discussion was to convert next_setting attribute (which is in UTC) to EST time so Time trigger would execute on that time.
This is the code for sensor

  - trigger:
      - platform: time
        at: '00:00:00'
      - platform: event
        event_type: event_template_reloaded
      - platform: homeassistant
        event: start
    sensor:
      - 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

I subtracted 300 minutes (5 hours) to change the UCT to EST) that is why the test shows 7:36 am

sun.sun’s attributes are fully fleshed out UTC timestamps. If you subtract 5 hours, you’re actually incorrectly changing the time by 5 hours.

Just to clarify, a utc timestamp…

2022-01-29 12:26:16.413162+00:00

is identical to a timestamp local to your TZ, but it has the offset built into it

2022-01-29 07:26:16.413162-05:00

What you did is took

2022-01-29 12:26:16.413162+00:00

and subtracted 5 hours…

2022-01-29 07:26:16.413162+00:00

which is

2022-01-29 02:26:16.413162-05:00

which explains why you’re 5 hours off and it’s happening at 2 am.

That confirms my suspicion that you purposefully set back the time by 5 hours and explains why the automation triggered at 2:38 EST (instead of 7:38 EST or its equivalent of 12:38 UTC).

Respectfully, this entire issue appears to be due to your misunderstanding of how time is handled in Home Assistant, specifically time zones.

Petro has provided a clear explanation of what you have been misinterpreting.

1 Like