Recording last ON state duration

I’ve a binary sensor and I’d like to make visible oin the frontend its last time when it went OFF and also the duration of the élast ON state.
The first is OK, I could manage but I don’t know how to create a sensor or any other entity to be able to put on the UI the duration of last ON state. It has to start when the binary sensor goes ON and stop when it is go OFF (or unknown state maybe). And it has to restart when it goes ON again.

You’ll need to setup a history stats sensor in your config. I’ve pasted my code on how I track the duration of my furnace running below. Just substitute the appropriate entity and state for your use.

And then I track it in a mini-graph card to compare daily usage (see below for that code too… but you’ll need to install the custom mini-graph card from HACS if you haven’t already… or just use the built-in history graph.)

# History Stats for Furnace
  - platform: history_stats
    name: FurnaceOnToday
    entity_id: sensor.thermostat
    state: 'heating'
    type: time
    start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
    end: '{{ now() }}'

type: custom:mini-graph-card
name: Furnace Usage
icon: mdi:fire
  - entity: sensor.furnaceontoday
hours_to_show: 120
points_per_hour: 2
smoothing: false
refresh_interval: 0
aggregate_func: last

I was looking after the history stats but to be honest I don’t know how can it solve my problem. In your example the history stat starts at the beginning of every day and stops at the current time. But I need something which starts when an entity state goes ON (from OFF) and stops when it goes OFF from ON.
What I need the whole duration between the last on and off state (even if it was 2 months ago or just 2 hours ago).

Ah… I understand now. I believe you’ll still need the history stats… but the proper code to turn it back OFF when the state changes is a little beyond my skillset.

What if you made an input boolean that changed when the state changes and then base the history stats on the input boolean? (I’m just spit-balling here. Maybe someone smarter than me will chime in and assist.)

Currently my workaround to have two input datetimes and control them with automation. One records the date and time when it goes off and the other when it goes on and then I can use them to calculate the last ON time (when ON is smaller than OFF time).