Query to messure kWh from watts used

I’m trying to measure kWh (kilowatt-hours) used by a socket for a month, the query for actual watts used is working but I can’t figure out how I get it to add it all up so I get measurements from the last 31 days. Any help would be greatly appreciated.

The query for watts used

from(bucket: “Home-Assistant”)
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r[“_measurement”] == “W”)
|> filter(fn: (r) => r[“_field”] == “value”)
|> filter(fn: (r) => r[“domain”] == “sensor”)
|> filter(fn: (r) => r[“entity_id”] == “wiz_socket_22c2a2_strom”)
|> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
|> yield(name: “mean”)

Welcome @Hef to the InfluxDB forum.

There are a couple of ways to specify the start of the month, but I like this one:

import "date"
month = date.truncate(t: now(), unit: 1mo)

from(bucket: "Home-Assistant")
  |> range(start: month, stop: v.timeRangeStop)
  |> filter(fn:.....

Will look like this in Grafana:

Even nicer is to keep your Flux query as is, and use Grafana’s Time Picker and select This Month So Far:

Even better is to again keep your Flux query as is, and use the Relative Time field in Grafana as now/M

If you want to see the entire current month (with blank values for the days that have not yet elapsed), fill in the Time Shift as 0M/M

Note that these last two options (and the first one) override completely override Grafana’s Time Picker altogether.

Maybe just insert
|> sum()
after the aggregateWindow statement?