Calculate total time containing non-zero values for prometheus data source

Hi -

I created a dashboard to show my ecobee thermostat temperature and when the heat is on, using Home Assistant (Homekit controller) and Prometheus to scrape values.

How can I sum the total time that the heat is on over a given time period?

Edit1: How do i get the current time in nano or milliseconds since epoch?

Edit2: ok so it’s just time() … I’m getting closer, now I need to add some transforms.

I’m mainly trying to figure out about how much energy is used (gas furnace, I don’t think I can get that data without measuring the actual gas flow since BTU per volume can vary, but time on is good enough for me), but would also like to see ramp up times and maybe use those in the future.

The heat comes back as a binary / boolean, zero or one value.

If I could write code, I’d just iterate over each point in time and see if the heat is zero or one to figure out the stop / start times, and then sum the “on” intervals.

My current panel looks like this - I add a shaded area by multiplying the “heat on” by the current temperature, use a shaded area under it, have a hard minimum of 60F (otherwise the chart goes from zero to about 70F). I leave the “Heat On” visible so I can toggle it on and off:

I used the prometheus function sum_over_time() divided by count_over_time(), and that gave me fraction of the interval that the heat was on.

And then the total interval time is $__range_s

Prometheus query:

sum_over_time(homeassistant_climate_action{friendly_name="Thermostat", action="heating"}[$__range]) / 
count_over_time(homeassistant_climate_action{friendly_name="Thermostat", action="heating"}[$__range])

And then you can add transforms to show the percent and total time on over the selected time, and use gauges and some other hacks to get to this chart - not quite ideal, I should probably split out the “Time On” or display it better but good enough for now: