I am trying to create a sensor that updates if the current date is odd or even. So far i have it working as per the code below but it is not live, it only updates when the configuration files are loaded… i guess thats how now() works… I have a time_date sensor set up but need help on adding it to my code.
# Monitor if date is odd or even
- platform: template
sensors:
odd_even:
friendly_name: "Date Odd or Even?"
value_template: >-
{% if (now().strftime("%-d") | int % 2) == 0 %}
Even
{% else %}
Odd
{% endif %}
I have something fairly similar, try adding the entity as mentioned above.
# Monitor if date is odd or even
- platform: template
sensors:
odd_even:
friendly_name: "Date Odd or Even?"
value_template: >-
{% if (now().strftime("%-d") | int % 2) == 0 %}
Even
{% else %}
Odd
{% endif %}
entity_id: sensor.time
Determining if the current date is even or odd is a calculation that only needs to be performed once per day, just moments after midnight
Basing it on sensor.time means it will be evaluated every clock tick, so it’ll be doing that not once per day but umpteen times a day. Kind of a lavish use of CPU cycles for something that only needs to be done once, at the beginning of the day.
I don’t know what is your use-case for this even/odd sensor but you can have an automation, scheduled to run a few seconds after midnight, perform the calculation can then call a service or set an input_boolean (off=odd, on=even) or whatever.
To piggy back off @123, you can incorporate the date sensor (part of the time sensor), and use that instead. Also, you can simplify your template.
# Monitor if date is odd or even
- platform: template
sensors:
odd_even:
friendly_name: "Date Odd or Even?"
entity_id: sensor.date
value_template: "{{ 'Odd' if now().day % 2 else 'Even' }}"
or just having a binary_sensor to tell you if it’s an odd day:
Thanks for all the suggestions. The calculation only needs to be performed once per day so i have set up an automation that simply forces the sensor to update at 1 minute past midnight by calling the homeassistant.update_entity service and passing it the code as follows. Seems to work great
what I would like to do: a different value every day, but even Wednesdays assign a value, odd ones another value. Can you tell me where is the error on this code?
Please format your code so others can easily read it.
To format code, select it then click the </> icon.
Alternately, type three consecutive back-quotes ``` on a separate line before your code then three more on a separate line after your code