Percent of time State Spent between values

I am trying to understand states vs statistics and I have a goal in mind. I have an entity which reports its state every 5 minutes and it reports values between say 0 and 400. I have over 7 days of history now and I want to calculate how much time in the past 7 days has been spent with the value between two values (for example 100 and 200).

I am guessing the answer is a template sensor, but I cannot think of the best way of doing this.

Yeah, a template binary sensor that checks for the >100 and <200 state. Then history stats to count how long that sensor has been on in the last 7 days.

Unfortunately it will only start measuring from after you create the template binary sensor.