Calculating delta (change since last value)

Hi.
I’m trying to calculate the delta value (change since the last value, can be positive, negative or 0) between two blood sugar readings. The readings are updated every 5 minutes.
This is what I currently have:

  - platform: statistics
    entity_id: sensor.blood_sugar
    name: Blood Sugar Delta
    sampling_size: 2
    precision: 1
    state_characteristic: change
  - platform: template
    sensors:
      bgdelta:
        friendly_name: "BG Delta"
        value_template: >
             {{ states.sensor.blood_sugar_delta.state.split('.')[0] }}

This generally works as intended, except after a minute or so, the delta changes to 0 even though the value of sensor.blood_sugar is still the same.
Is there any way to prevent it from recalculating the delta value even though the blood value has not changed?

Doesn’t the statistics sensor give you delta in the attributes already?

Maybe I’m missing something but if the sensor value for 2 samples is the same then shouldn’t the delta actually be 0 between those two samples?

it sounds like it’s working as intended.

The problem is that no new sample arrived. The value only changes every 5 minutes (give or take a few seconds depending on transmission delays to the server), but it seems the delta is re-calculated even if no new value has arrived.

Unfortunately, the statistics sensor only gives me the attributes:
Buffer usage ratio
Source value valid

It may depend on what HA “thinks” constitutes a new sample arriving. I don’t know what the metric is but it’s likely something to do with “last seen” or “last updated” or something.

That’s my best guess on whats happening.

If you can’t figure it out using a statistics sensor you could use a triggered template sensor based on the state of the blood sugar sensor changing or using time at every 5 minutes if the value doesn’t change and then use a template to calculate the delta from the to_state and from_state.