Template for time span from sunset

I need a template which returns true for any time between sunset - 2 hours and sunset + 0.5 hours. For all other times, it should return false. So, if the sunset is at 7:45 PM, the template should return true between 5:45 PM and 8:15 PM.

I was wrongly assuming that offset in sunset would do this but on reading documentation, it turns out that offset from sunset is just a point in time. I am looking for a time span.

Thanks…

{% set sunset = states('sensor.sun_next_setting') | as_datetime | as_local %}
{% set start = sunset - timedelta(hours=2) %}
{% set end = sunset + timedelta(minutes=30) %}
{{ start.time() < now().time() < end.time() }}
2 Likes

If you are talking about the Sunrise/Sunset Condition, your goal can be accomplished with a pair of conditions:

...
condition:
  - alias: "sunset - 2 hours"
    condition: sun
    after: sunset
    after_offset: "-02:00:00"
  - alias: "sunset + 0.5 hours"
    condition: sun
    before: sunset
    before_offset: "00:30:00"
....

{% set sunset120 = as_timestamp(state_attr("sun.sun", "next_setting")) - 7200 %}
{% set sunset30 = as_timestamp(state_attr("sun.sun", "next_setting")) + 1800 %}
{% set time = as_timestamp(now()) %}
{% if [sunset120 < time] and [time < sunset30] %}
  true
{% else %}
  false
{% endif %}

This method will not return the correct value after sunset, because the sensor attribute will have rolled forward to the next day. This will cause sunset120 < time to be false.

That is why @123 included the time() method in his final expression. It avoids having the date roll over mess up the time comparison… at the cost of a few seconds of accuracy.

1 Like

well .time() isn’t needed because the date rollover is handled when you add a time delta to a datetime. The template is essentially the same

{% set sunset = states('sensor.sun_next_setting') | as_datetime | as_local %}
{% set start = sunset - timedelta(hours=2) %}
{% set end = sunset + timedelta(minutes=30) %}
{{ start < now() < end }}

But from sunset until midnight, now() will be today and sunset will be tomorrow… so the 30 minutes after sunset will be false when they should be true.