Attributes of two sensors: filter dates, multiply and sum corresponding values

Hello all,

I have a problem with which I am unfortunately stuck. There are 2 sensors that output both datetime and a value as an attribute. I would like to calculate something with these values.

sensor.sensor_1

state_class: measurement
data: 
- datetime: '2022-07-06T11:00:00.000Z'
  value: 0
- datetime: '2022-07-06T12:00:00.000Z'
  value: 3
- datetime: '2022-07-06T13:00:00.000Z'
  value: 1
- datetime: '2022-07-06T14:00:00.000Z'
  value: 4
...

sensor.sensor_2

state_class: measurement
data: 
- datetime: '2022-07-06T11:00:00.000Z'
  value: 5
- datetime: '2022-07-06T12:00:00.000Z'
  value: 2
- datetime: '2022-07-06T13:00:00.000Z'
  value: 6
- datetime: '2022-07-06T14:00:00.000Z'
  value: 7
...

I would like to achieve the following:

  • Restrict the datetime attributes to a certain time range (e.g. only until 2022-07-06T13:00:00.000Z).
  • For this restricted time range, multiply each value of the two sensor attributes with equal daretimes, i.e.: [0*5, 3*2, 1*6].
  • Sum up the respective products of the previous step, i.e.: 0*5 + 3*2 + 1*6 = 12.

Specifically, I would like to apply this to sensors of the HACS integration https://github.com/FL550/dwd_weather

  • sensor.precipitation_probability_STATION
  • sensor.precipitation_STATION

Can someone help me here? Thank you very much in advance. :heart:

This could be done via a Jinja template. E.g.:

{% set last = "2022-07-06T13:00:00.000Z" %}
{% set data1 = [
  {"datetime": "2022-07-06T11:00:00.000Z", "value": 0},
  {"datetime": "2022-07-06T12:00:00.000Z", "value": 3},
  {"datetime": "2022-07-06T13:00:00.000Z", "value": 1},
  {"datetime": "2022-07-06T14:00:00.000Z", "value": 4},
] %}
{% set data2 = [
  {"datetime": "2022-07-06T11:00:00.000Z", "value": 5},
  {"datetime": "2022-07-06T12:00:00.000Z", "value": 2},
  {"datetime": "2022-07-06T13:00:00.000Z", "value": 6},
  {"datetime": "2022-07-06T14:00:00.000Z", "value": 7},
] %}
{% set ns = namespace(sum=0) %}
{% for i in range(data1|length)
   if data1[i].datetime|as_datetime <= last|as_datetime %}
  {% set ns.sum = ns.sum + data1[i].value * data2[i].value %}
{% endfor %}
{{ ns.sum }}

If you did this in, say, a template sensor, then the “set data1” and “set data2” lines would probably change to:

{% set data1 = state_attr('sensor.precipitation_probability_STATION', 'data') %}
{% set data2 = state_attr('sensor.precipitation_STATION', 'data') %}

I’m not sure how you would pass in the “last” value. Maybe you could set that in an input_datetime entity, and then the first line would change to something like:

{% set last = (states('input_datetime.last') ~ 'Z')|as_datetime %}
1 Like