Hey everyone,
I do have a question of this kind.
So I have a templated sensor that takes the value of a temp sensor from, say, 8am to 8pm, and then the value of another the rest of the time. Actually, the 8am and 8pm values are taken from 2 time inputs.
Until today, I was doing something like this (with added “debugging” code):
{% set n = now().time() %}
{% set b = now().fromtimestamp(state_attr('input_datetime.heater_target_rooms', 'timestamp')).time() %}
{% set e = now().fromtimestamp(state_attr('input_datetime.heater_target_living', 'timestamp')).time() %}
{% if (b >= e and (n >= b or n < e)) or (b < e and (n >= b and n < e)) %}
{{ states.sensor.temperature_1.state }}
{% else %}
{{ states.sensor.temperature_2.state }}
{% endif %}
{{ n }}
{{ states('input_datetime.heater_target_rooms') }} -> {{ b }}
{{ states('input_datetime.heater_target_living') }} -> {{ e }}
Which outputs the following:
20.9
23:32:00.002545
21:00:00 -> 22:00:00
06:45:00 -> 07:45:00
We can see I had a problem with an offset hour being added to my target times. Now, I do understand this is due to not passing the timezone argument when calling “fromtimestamp” (I’m ashamed to say I did not get how to do that from a template). Reading this thread, I convinced myself this was unnecessarily complex and tried to replace now()
with the time sensor I’m already using for automations.
This leads to this code, which is indeed simpler and actually gives the correct result:
{% set n = states('sensor.time') %}
{% set b = states('input_datetime.heater_target_rooms') %}
{% set e = states('input_datetime.heater_target_living') %}
{% if (b >= e and (n >= b or n < e)) or (b < e and (n >= b and n < e)) %}
{{ states.sensor.temperature_1.state }}
{% else %}
{{ states.sensor.temperature_2.state }}
{% endif %}
All should be well, but I’m a bit uneasy, because I’ve got the feeling I’m now comparing strings instead of comparing times. I know said strings include leading zeros so string comparison should work fine, but it still feels a bit off to me. Should I indeed worry or should I just stop obsessing with this and happily go back to trying to understand how the whole media_player thing is supposed to let me play something to a local bluetooth sink ?
Anyways, thanks a lot for HA, which is indeed an amazing piece of software, particularly combined with the myriad other open source software that it plays nice with. The HA crowd is amazing