How to calculate kwh in a specific time period each day?

Hi,
the graph shows a cumulative kWh value over the day. The value is set to 0 at 0:00 each night. I would like to calculate the kWh each day in a specific time period from 10:00-16:00. Because it is a cumulative value already which is summed up by homewizard, my approach is to calculate a delta (16:00 value minus 10:00 value). How could I solve this with flux?

My approach was:

import "date"
import "timezone"
option location = timezone.location(name: "Europe/Berlin")

data1 = from(bucket: "homey-downsample")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "Wattcher")
  |> filter(fn: (r) => r["_field"] == "meter_power")
  until_16 = data1
  |> filter(fn: (r) => {hour = date.hour(t: r._time) return hour == 16})
  |> aggregateWindow(every: 1d, offset: -1s, fn: max, createEmpty: false)
  |> set(key: "_field", value: "delta")
  until_10 = data1
  |> filter(fn: (r) => {hour = date.hour(t: r._time) return hour == 10})
  |> aggregateWindow(every: 1d, offset: -1s, fn: max, createEmpty: false)
  |> set(key: "_field", value: "delta")
  union(tables: [until_16, until_10])
  |> difference()
  |> aggregateWindow(every: 1d, offset: -1s, fn: max, createEmpty: false)

But it doesn’t work and I do not trust the result.

THX for your help in advance!

I hope this example can help you.
In this case the number of errors is incremental and this graph shows the errors that occurred in v.windowPeriod

Thx @Giu-seppe especially you are the only one how answered! But your answer didn’t full fill my needs or I didn’t understand it.

Here is the solution I worked out myself, maybe it will help someone:

import "timezone"
option location = timezone.location(name: "Europe/Berlin")

data1 = from(bucket: "homey-downsample")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "Wattcher")
  |> filter(fn: (r) => r["_field"] == "meter_power")
  until_16 = data1
  |> hourSelection(start: 16, stop: 16)
  |> aggregateWindow(every: 1d, offset: -1s, fn: min, createEmpty: false)
  |> set(key: "_field", value: "_16")
  until_10 = data1
  |> hourSelection(start: 10, stop: 10)
  |> aggregateWindow(every: 1d, offset: -1s, fn: min, createEmpty: false)
  |> set(key: "_field", value: "_10")
  union(tables: [until_16, until_10])
  |> group()
  |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")
  |> map(fn: (r) => ({time: r._time, kWh_10_16: float(v: if exists r._16 and exists r._10 then r._16-r._10 else 0.0)}),)
1 Like