Template for per instance water used instead of daily total

I have a smart water filter/softener that tracks my daily water usage throughout the day (the softer automatically resets the gallon count to 0 at midnight each night).

I want to make a template or history stat that tracks it on a more gradual level and find out how many gallons were used between recordings, not an overall accumulation total for the day.

So if the water is turned on at 20 gallons and then turned off at 30 gallons the sensor shows 10 gallons used at the last instance. The the next time the water is turned on at 30 gallons and off at 45 the sensor shows 15 gallons.

I would think it would have to reset to 0 at midnight so the first recording isn’t negative in the morning too?

I’d also like a sensor for the last time water was used / turned on…are these possible via templates?

It would help if you gave us some details about the available data sources.

Here’s a basic outline…

  - trigger:
      - platform: state
        entity_id: binary_sensor.is_water_flowing
        to: 'on'
        from: 'off'
      - name: Flow meter last value
        state: "{{ states('sensor.water_meter') }}"
      - name: Water last on
        state: "{{ now() }}"

  - sensor:
      - name: Water Quantity Last Instance
        unit_of_measurement: Gal
        state: >
          {% if is_state('binary_sensor.water_flowing', 'off') %}
          {% else %}
            {{ states('sensor.water_meter') | float(0) 
            - states('sensor.flow_meter_last_value') | float(0) }}
          {% endif %}
      - name: Water Last On Duration
        unit_of_measurement: hours
        state: >
          {% if is_state('binary_sensor.water_flowing', 'off') %}
          {% else %}
            {{ (now() - states('sensor.water_last_on') | as_datetime).total_seconds/3600 }}
          {% endif %}