Problem with odd and even week sensor

Hi, i’ve a problem with a sensor date to indicate an odd or even week.
This is my sensor:

  - platform: template
    sensors:
      current_week:
        value_template: >-
          {% set year = states.sensor.date_time.state.split(',')[0].split('-')[0] %}
          {% set month = states.sensor.date_time.state.split(',')[0].split('-')[1] %}
          {% set date = states.sensor.date_time.state.split(',')[0].split('-')[2] %}
          {% set today = strptime(year ~ '-' ~ month ~ '-' ~ date , '%Y-%m-%d') %}
          {%- if (as_timestamp(today) | timestamp_custom('%U', true) | int ) % 2 == 0 -%}
            Settimana pari EVEN (# {{ as_timestamp(today) | timestamp_custom('%U', true) }})
          {%- else -%}
            Settimana dispari ODD (# {{ as_timestamp(today) | timestamp_custom('%U', true) }})
          {%- endif -%}

The problem is that today is 27 march (it will be 13# week of the year… ) but the sensor show me:

Settimana pari EVEN (#12).
I don’t know where is the problem…

Try this:

  - platform: template
    sensors:
      current_week:
        entity_id: sensor.date
        value_template: >-
          {% set week_number = now().isocalendar()[1] %}
          Settimana pari {{'EVEN' if week_number % 2 == 0 else 'ODD'}} (#{{week_number}})
1 Like

Hi, thanks for suggest.
But what i know is that now() should not be used inside a template sensor cause don’t partecipate to update the sensor…

That’s why I’ve included:

entity_id: sensor.date

The template sensor will trigger whenever sensor.date changes state. Then it proceeds to evaluate value_template.

Without entity_id: sensor.date, the template sensor will only be evaluated when Home Assistant starts because, as you pointed out, value_template has no entity and only uses now().

1 Like

Ok this is more clear to me! Thanks for the trick!

I think that depends on which system of calculation you are using.

And depending on which system the end result you are trying to achieve uses it may make a difference on which system you will need to use.

according to the unix datetime system that you used originally this date (mar 27) actually is in week #12. But according to the isocalendar system used by @123 in their template the same date is in week is #13.

You have to determine which system your target use case also uses or you may be off a week in your template.

I need to use calculation to retrieve value as @123 suggest. I need to show 13.
One question i’m curious… Why two system differ to one week??

https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm

The best I can figure is that the calculation for the ISO calendar starts at week 1 the other calendar starts at week 0.

1 Like