How to keep track of time between state changes?

I have been messing around with history_stats and cannot figure out a weay to do this.

I am looking for a way to track the amount of time between runs of my sump pump.

So i have a sonoff smart switch flashed with esphome, so I am monitoring power usage and I am getting a binary sensor on/off state based on if the sump pump is running.

I am looking for a way to track the amount of time between activations of the sump pump so I can have a card that basically states “Time between runs” using the last time value it previous was off.

e.g. Sump Pump Time between runs: 15 minutes

The closest I have got is below, which seems to keep track of time off, but it only displays the time since it turned off, not the previous time before.

  - platform: history_stats
    name: 'Sump Pump Time Between Runs'
    entity_id: binary_sensor.sump_pump_status
    state: 'off'
    type: time
    start: "{{ as_timestamp(states.binary_sensor.sump_pump_status.last_changed) }}"
    end: "{{ now() }}"

Perhaps this can be of assistance?

I’m not sure it’s best way but the way I would do it is to create two input_datetimes - one for the current turn on time (DT1) and one for the previous turn on time (DT2)

then in an automation set the input_datetimes.

psuedo-code:

trigger - sump pump turned on.
action - set DT2 to the value of DT1 then set the DT1 to now()

that way you always have times that the pump turned on recently and the one prior to that.

then create a sensor to give you the time between the two values (DT1 - DT2).

then you can graph that sensor over time.

1 Like

I use a slightly different approach. I found myself always looking at the graph and counting the spikes. Eventually it dawned on me that what I really wanted was how many time it came on in the past hour. Here’s how I did that:

sensor:
  - platform: history_stats
    name: East Pump On 1H Count
    entity_id: binary_sensor.east_pump_cycle_on
    state: "on"
    type: count
    end: "{{ now() }}"
    duration:
      hours: 1

The binary sensor I’m using to detect each cycle is a template based on the current monitoring sensor of the smart plug it’s plugged into:

template:
  - binary_sensor:
      - name: "East Pump Cycle On"
        unique_id: 'east_pump_on'
        state: "{{ states('sensor.east_sump_pump_current')|float > 1 }}"

For reference, the current sensor reports Amps, and the pump normally pulls somewhere between 2 and 3 Amps, so I just use > 1 as the indicator that it’s on.

Obviously you could do more, like divide 60 by the number of cycles to get average minutes between cycles. But I’m finding just the count per hour is easy to grasp. Obviously it doesn’t have to be one hour, you could do any number of hours or days. I have a field stone foundation surrounded by clay so most of the year my number per hour is greater than one!

1 Like