How to template a period of time condition

Hi,

I’m trying to create a condition for an automation that looks to see if we’re in a certain period of the year. So for example, January to March is one period, March to August is another.

Is there any way of having Home Assistant check if we are currently within either periods of time when executing an automation?

Something like this seems to test okay when I plug it in.

{% if now().month in [1,2,3] %}
  this
{% elif now().month in [3,4,5,6,7,8] %}
  that
{% else %}
  or something else
{% endif %}
1 Like

Although…I’m not sure what happens since 3 falls in both ranges.

Thank you for your reply, that looks promising. I have kind of circumvented it by using a dedicated calendar for checking condition. I’ll look into your solution, though, it seems neater. Thank you

Building on @arretx’s suggestion, I always recommend copying the result of now() into a temp variable in a template if the template will use its value more than once. This way the value will be consistent. Also, you can use a compare expression as an alternative. Lastly I suspect you don’t want periods to overlap (i.e., in your example, March was in the first and second period.) So:

{% set month = now().month %}
{% if 1 <= month <= 3 %}
  this
{% elif 4 <= month <= 8 %}
  that
{% else %}
  or something else
{% endif %}

… and this particular case of month ranges could be simplified to:

{% set month = now().month %}
{% if month <= 3 %}
  this
{% elif month <= 8 %}
  that
{% else %}
  or something else
{% endif %}
1 Like

That’s great, thank you!