Update operating hours of 3D-printer

Hi there

I recently bought a Bambulab P1S and would like to collect its operating hours. I found this thread Operating hours counter? but cant get it to work. This is how my code looks like:

I asked Chat-GPT and got the below code which is working fine EXCEPT when HA restarts the value of the template-sensor resets to 0.0

  - platform: template
        friendly_name: "Printer operating Time"
        unit_of_measurement: "hours"
        value_template: >-
          {% if is_state('sensor.p1s_XXX_print_status', 'running') %}
            {% set start_time = states.sensor.p1s_XX_print_status.last_changed %}
            {% set current_time = now() %}
            {{ ((current_time - start_time).total_seconds() / 3600) | round(1) }}
          {% else %}
          {% endif %}
          last_value: "{{ states('sensor.printer_operating_time') | float }}"

Is there any way to keep the last value before a restart? the goal is that the values in the template-sensor accumulates. I tried it with the last_value but it doesnt work.

I would be glad to get some assistance, I spent hours of research but cant figure out what I am doing wrong.

all the best


You can use a History Stats sensor to track runtime either over a specific time period or per instance. To accumulate the times in a way that will survive restart you will need a either a trigger-based template sensor or a Utility Meter sensor.

thanks for your quick reply, after having some patience I noticed that the utility meter works just fine, it took some time to update.

If somebody else tries to build an operating hours counter, here is my code.

  - platform: history_stats
    name: printer operating history
    entity_id: your.printer
    state: "running"
    type: time
    start: "{{ now().replace(hour=0, minute=0, second=0) }}"
    end: "{{ now() }}"

then create a utility meter which pulls the data from your history_stats sensor. I used h (hours) as the tariff inside the utility-meter.