Counting number of sensors below a certain number

I am trying to count the number of sensors (one sensor for the power price each hour) that have a state below a certain value specified in the sensor “sensor.car_charge_limit_tomorrow”. The sensor calculates how many hours of charging I will get in my car during the night. Everything works as intended, but not when there is a negative price on the power, despite its being lower than the limit.
Any suggestions? I have borrowed this code, so I am not the author of this.

- platform: template
  sensors:
    hours_with_charging_tomorrow:
      friendly_name: 'Hours with charging tomorrow'
      unit_of_measurement: hours
      value_template: >-
        {% set ignore_entities = ['sensor.nordpool_tomorrow_hr_00_01', 'sensor.nordpool_tomorrow_hr_01_02', 'sensor.nordpool_tomorrow_hr_02_03', 'sensor.nordpool_tomorrow_hr_03_04', 'sensor.nordpool_tomorrow_hr_04_05', 'sensor.nordpool_tomorrow_hr_05_06', 'sensor.nordpool_tomorrow_hr_06_07', 'sensor.nordpool_tomorrow_hr_07_08', 'nordpool_tomorrow_hr_08_09'] %}
        {% set limit = (float(states('sensor.car_charge_limit_tomorrow'))*100) %}
        {{ states.sensor
          | selectattr('attributes.device_class', 'eq', 'aqi')
          | rejectattr('entity_id', 'in', ignore_entities)
          | map(attribute='state')
          | reject('in', ['unknown', 'unavailable'])
          | map('int', -1) | select('le', limit)
          | select('ge', 0)
          | list | count
        }}

Because this line selects values greater than, or equal to, zero so all negative values are excluded.

| select('ge', 0)

Remove the line if you want the template to include negative values.

Ah, thanks.
Works like a charm!
Thanks a lot.!

1 Like

You’re welcome!

Please consider marking my post above with the Solution tag. It helps others who may have similar questions to find answers.

For more information about the Solution tag, refer to guideline 21 in the forum’s FAQ.