Template, compare last 2 state change timestamps

I have the below template that shows how long my washing machine has been running while it’s on. It compares the current time to the time of the last change (when it was turned on).

{%if states('binary_sensor.washing_machine_on_template') == 'on' %}
Washing machine on for {{(as_timestamp(now()) - as_timestamp(states.binary_sensor.washing_machine_on_template.last_changed)) | timestamp_custom("%H:%M:%S", false) }}
{% else %}
Washing machine off
{% endif %}

Currently, when it’s off, it just says that it’s off. I’d like it to show the total time it had last been running when it’s off. How do I compare the last changed time to the time it changed prior to that?

A wild guess would be to just add the same template as you have when on.
It should only update once, when it just turned off so the time should be the same (or possibly a minute more) than it was when it was on.

The template calculates the last state change to “now”.

If I use the same calculation, it will just show me how long the washer has been off instead of how long it’s been on.

If you need it to survive restart and reload, then you would need to store the value in another helper. Otherwise, you can use the this variable to retrieve the last state of the sensor itself:

{% set ent = 'binary_sensor.washing_machine_on_template' %}
{% if states(ent) == 'on' %}
  Washing machine on for {{(as_timestamp(now()) - as_timestamp(states[ent].last_changed)) | timestamp_custom("%H:%M:%S", false) }}
{% else %}
  {{ this.state | default('No current value', true)}}
{% endif %}

No because the state change of the sensor will only happen when the machine switches state.

Assuming it’s a triggered template sensor.
Not sure what will happen if it’s a normal sensor.

Actually, it was a template used in a markdown card, so I don’t think that would work. I’m going to try Didgeridrew’s template as a template sensor to see how that works.

I’m testing this out now, the original template I was using was in a markdown card on a dashboard, not a sensor.

So far, the template sensor does not update as well as the markdown card (when I load the dashboard, the markdown card will show the latest time, the sensor might be lagging a little, but once the dashboard is loaded, it looks like it will eventually update to match the card template).

I’ll see how the template works out, and if it does what I need to show the time it had run when off, i’ll use the ‘on’ status in the markdown card as is, and display the ‘off’ status of the template sensor.