Getting the duration of previous state of a sensor

I’m using an A2DP sensor to see how long my commutes are (phone connected to car = sensor is ‘on’).
I would like to push a notification to my phone telling me how long I’ve driven at the moment the A2DP sensor turns to ‘off’.

To be able to do so I would need to know the duration of the previous state (which is ‘on’). Things coming to mind is starting/stopping a timer, using input fields to store the timestamps , perhaps a statistics sensor?

But perhaps there is an easier way to grab this data as HA is already recording it and the History graph card can show it?

I’d like to know this as well. I need to see how long my coffee maker is in the off state before it turns on.

There are a few ways, but the History Stats integration is what comes to mind first. You may need to also use a Template sensor to focus what the History stats sensor counts.

Another option is to use an automation to store the timestamp values in a helper or variable.

This discussion is old, but instead of creating a new thread I think its better to continue here. It is possible to have a condition based on the duration of the previous state when the state change of the entity is the trigger of the automation. In my automation I use the state change of a light entity to trigger the automation under the condition it has been switched from off to on and back to off within 0.3s. Effectively using the light switch as a type of pulse switch.

  - platform: state
      - light.buitenlamp_voordeur
    to: "off"

The condition template is true when the previous state has last less than 0.3s:

       - condition: template
          value_template: >-
          alias: Previous state last for less than 0.3seconds

This template is based on: