Getting an average reading of a sensor during certain hours

I have a PoolSense integration with Home Assistant. It works really well and records values every few hours. However, I am using the in-line version of the sensor, so the readings are only accurate during the time which the pool pump runs, in my case between 10h00 and 15h00. What I am trying to achieve is to calculate the average pH and Chlorine levels during these hours and then report those readings to me on a daily basis to allow me to treat the pool appropriately. Here is the template I have created, but I am just getting “unavailable” as a reading :frowning_face:

  - platform: template
        friendly_name: "Average pH Reading"
        value_template: >-
          {% set start_time = states("sensor.date_time") + " 10:00:00" %}
          {% set end_time = states("sensor.date_time") + " 15:00:00" %}
          {% set readings = states.sensor.poolsense_ph.attributes.values() | selectattr('last_updated', 'ge', start_time) | selectattr('last_updated', 'le', end_time) | map(attribute='state') | map('float') | list %}
          {{ readings | average }}

And here is a screenshot of the sensor state:

I have been trying all sorts of tweaks, but I am still relatively new to templates, so I am just getting frustrated rather than achieving anything.

Any help or advice would be gratefully received.

So a couple things:

  1. This refers to sensor.date_time. Where and how is that defined? What is the value of it? This doesn’t seem to be a default sensor that I can reference in my instance. Check that it is setting the value you expect it to be.

  2. last_changed is not an attribute of an entity. Have a look at this thread for a bit of an explanation:
    Last_updated State and last-changed in Lovelace - Configuration - Home Assistant Community (
    In my instance, I have used states.sensor.entity_id.last_changed and this gives me the value I want.

  3. Once you have corrected the above, go to Developer Tools, then the Template tab and copy what you’ve got straight into that box. It will give you the output of the template and tell you if there are errors (such as a sensor being undefined, the wrong type being used, etc) and you can correct from there. You can also add in things like {{ start_time }} to view and double check that the value in that variable is what you were expecting.

Good luck and let me know how it goes.

1 Like

Assuming this sensor only has a date: sensor.date_time you would be better off doing this:

          {% set start_time = today_at('10:00:00') %}
          {% set end_time = today_at('15:00:00') %}

Putting aside what Sam said above about last_updated being a property of the state object and not an attribute, even if it was an attribute I think this would be comparing strings, not datetime objects:

selectattr('last_updated', 'ge', start_time)

So you may not get the results you expected. e.g. when comparing strings (left to right) “2” is ge than “12”.