Create an average duration sensor with long term statistics

Hi, I’ve built some sensors for my drying machine:

  • Number of drying cycles
  • Total drying time
  • Average drying cycle duration (which is a division of the above 2)

but in these last days I’ve been burning my head on how to create this average cycle duration as a long term statistics.

Here’s what I currently have:

  - platform: history_stats
    name: Total drying time
    entity_id: input_boolean.drying_or_not
    state: "on"
    type: time
    start: "{{ now().replace(day=1).replace(hour=0).replace(minute=0).replace(second=0) }}"
    end: "{{ now() }}"

  - platform: history_stats
    name: Nb drying cycles
    entity_id: input_boolean.drying_or_not
    state: "on"
    type: count
    start: "{{ now().replace(day=1).replace(hour=0).replace(minute=0).replace(second=0) }}"
    end: "{{ now() }}"

input_boolean.drying_or_not is a helper toggle sensor, updated by 2 automations:

  • If automation detects there’s a drying cycle, input_boolean.drying_or_not=on
  • If automation detects drying cycle has ended, input_boolean.drying_or_not= off

I also created another helper sensor, a Date and/or time, input_datetime.average_drying_cycle, and I set this with the following formula in the automation that detects the end of the drying cycle:

{{ (states('sensor.total_drying_time') | float(0) * 3600 / states('sensor.nb_drying_cycles') | float(0)) | timestamp_custom('%H:%M:%S', False) }}

The calculation is done correctly, but I wanted to have long terms statistics for this average cycle time.

I tried also to create a sensor from this helper, and also another sensor with the direct calculation, and added a customization to try to create the long term statistics without success:

  - platform: template
    sensors:
      average_drying_time:
        value_template: "{{ states('input_datetime.average_drying_time') }}"
        device_class: duration
      average_drying_time_new:
        value_template: "{{ (states('sensor.total_drying_time') | float(0) * 3600 / states('sensor.nb_drying_cycles') | float(0)) | timestamp_custom('%H:%M:%S', False) }}"
        device_class: duration

  customize:
    sensor.average_drying_time:
      state_class: total
    sensor.average_drying_time_new:
      state_class: total

What am I missing here? Is this possible to create?