Entity Ontime using History Stats

How does one count the Ontime of the state of a switch from on to off time, not from start of day?
e.g.
Start at zero
Count up in minutes
Stop the count when the state changes to off
Then when the state turns back on Start at zero again?

I guess I want the start stop and duration based on the entities state, not a time or day.
History Stats
This looks like the closest example but uses start at the beginning of the day.

sensor:
  - platform: history_stats
    name: Relay Ontime
    entity_id: switch.off_wall_sw_relay_1
    state: "on"
    type: time
    start: "{{ now().replace(hour=0, minute=0, second=0) }}"
    end: "{{ now() }}"

You probably want something related to last changed.

I built two automation’s and a helper counter, One triggers every minute and increments the counter if the state is on… The other automation clears the counter if the state is off.

Thanks KTibow