Average time interval between to consecutive state changes in a numeric sensor

I’m trying to define the following sensor for my 3d printer with no success, perhaps you can help me to understand what I’m missing?

I have at my disposal:

  • A sensor with the time elapsed from the start of a print
  • A sensor with the current layer of the current print job

What I’m trying to get is a sensor that show the time needed to print a given layer, so I can plot in an instogram.

Arithmetically is quite simple: calculate the difference in elapsed time between two consecutive changes in sensor.current_layer.

Then, another sensor to calculate the moving average time, for the current print job only (thus, this would reset when sensor.elapsed_time goes back to zero I guess)

But how to do that in a template? ?_?