Maybe someone has a better idea or maybe this will help someone. I wanted to create a template sensor that only showed the count of windows that had been open for at least 2 minutes.
I tried to do it with just selectattr
but failed when I got to trying to evaluate time. So I then tried it in a pure for if
loop but that doesn’t actually trigger. Changing it to loop on open windows with the if being the time eval worked out though. Here’s what I ended up with.
{% for item in states.binary_sensor | selectattr('state', 'eq', 'on')| selectattr('attributes.device_class', 'eq', 'window') if (as_timestamp(item.last_changed) < (as_timestamp(now())-120)) %}{% if loop.last %}{{ loop.index }}{% endif %}{% else %}0{% endfor %}
So I get all the open windows and check if they were last changed over 2 minutes ago. Then in the loop I return the current index if I’m at the end, or if I found nothing to loop then 0.
Why? I was getting frustrated having too many automations and conditions in them to figure out when to turn on/off my hvac away mode based on open windows and occupancy. Now I have a template sensor for my hvac status
{% if is_state('sensor.occupancy_status', 'home') and states('sensor.window_2min_count')|int < 2 %}enabled{% else %}disabled{% endif %}
Which is used in 2 automations to trigger setting away/home mode.
Hope someone finds it useful.