How to know if a hourly weather timestamp is between sunset and runrise

I am trying to get a template together to set the correct weather icon (mainly for cloudy state, to add the sun or moon symbol) but I can’t get the correct template to know if it is between sunset and sunrise.

I am using the OpenWeatherMap hourly data to display the state of the next 4 hours. But if it is in the evening and it is classed as partly cloudy it always shows it with a sun, while it should be with a moon. The template I have now doesn’t work right since it still shows a sun since either of the 2 if statements is true.

{% set cond0 = state_attr('weather.openweathermap_hourly', 'forecast')[0].condition %}
{% set next_setting = as_timestamp(state_attr('sun.sun', 'next_setting')) %}
{% set next_rising = as_timestamp(state_attr('sun.sun', 'next_rising')) %}
{% set cond0_time = as_timestamp(state_attr('weather.openweathermap_hourly', 'forecast')[0].datetime) %}

{% if cond0_time > next_setting and cond0_time < next_rising %}
  {% if cond0 == 'sunny' %} night {% elif cond0 == 'partlycloudy' %} night-partly-cloudy {% else %} {{ cond0 }} {% endif %}
{% else %}
  {{ cond0 }}
{% endif %}

The check if cond0_time > next_setting won’t ever be valid since as soon as the sun has set, it will be set to the next days new sunset timestamp.

Does somebody have a working template or suggestions how to resolve this?

I modified one the custom cards to achieve the same…although this is not a template, it may show the logic I applied

((datetimehourly > nextsetting && datetimehourly < nextrising) || (datetimehourly < nextsetting && datetimehourly < nextrising && nextrising < nextsetting))

You might be able to use the status of the sun, since when it is below_horizon then next setting will not be valid for your comparison.

Thanks for that example. I have translated it to:

{% if ((cond0_time > next_setting and cond0_time < next_rising) or (cond0_time < next_setting and cond0_time < next_rising and next_rising < next_setting)) %}

and will see if this works :slight_smile:

It took me a while too…added to that the constant restart of HA to see if it worked.
This is what I have now, based on a meteo-france card which did not work for hourly values
BTW, you can always try by updating the openweather attribs manually …
image

Just done a manual update of the attribute to see if it was working. And only 16:00 now showing it as “night-partly-cloudy”:
image

So seems to do as expected. Thanks for that tip :slight_smile: