Get duration of a value of a percentage sensor

Hi all,

I want to calculate the charging speed of a battery. The battery has a percentage sensor that updates every so often. I have already made a template that can calculate the difference between each update (e.g. 47%-51%=4% diff.) and from there calculates it to kWh. Now, to calculate kW, I need the time it needed to get from 47% to 51%.

In this example, the battery was at 47% at 12:58:06 and reached 51% at 13:12:06. This means 14 minutes. Unfortunately, it does not update at regular intervals, sometimes it only updates once or twice during a charging session (3-4h). Using history_stats, it is easy to get the duration when a sensor is a specific state (on or off) Problem is, that only works for binary sensors, not for percentage sensors. I have searched far and wide but none of the solutions work.

Any help or input is greatly appreciated.