AggregateWindow or Window backwards in time

You can’t window back in time but you can…

You can use an offset to make the window always align with the now time. if you add option offset = duration(v: int(v: now())) and then add the offset in your aggregateWindow call, that might give you what you want.

option offset = duration(v: int(v: now()))

data = from(bucket: "system")
  |> range(start: -1m)
  |> filter(fn: (r) => r["_measurement"] == "cpu")
  |> filter(fn: (r) => r["_field"] == "usage_guest")
  |> filter(fn: (r) => r["cpu"] == "cpu-total")
  |> filter(fn: (r) => r["host"] == "Anaiss-MBP.attlocal.net")
   |> yield(name: "data")

data 
  |> aggregateWindow(every: 30s, fn: mean, createEmpty: false)
  |> yield(name: "mean")

data 
  |> aggregateWindow(every: 30s, fn: mean, createEmpty: false, offset: offset)
  |> yield(name: "offset")

You could calculate the duration difference between your start time and the required start time so that your windows align with stop time and then add that duration to the offset. Something like:

 data = from(bucket: "Air sensor sample dataset")
  |> range(start: 2021-08-19T19:23:37.000Z, stop: 2021-08-19T19:24:18.000Z )
  |> filter(fn: (r) => r["_measurement"] == "airSensors")
  |> filter(fn: (r) => r["_field"] == "co")
  |> filter(fn: (r) => r["sensor_id"] == "TLM0100")
  |> limit(n:5)

data
  |> yield(name: "mydata")

lastpoint = data |> last() |> findRecord(fn: (key) => true , idx:0 )
firstpoint = data |> first() |> findRecord(fn: (key) => true , idx:0 )

time1 = uint(v: firstpoint._time)
time2 = uint(v: lastpoint._time)

mywindow = uint(v: 15s) 

remainder = math.remainder(x: float(v:time1) - float(v:time2), y: float(v:mywindow))
myduration = duration(v: uint(v: remainder)) 

data
  |> aggregateWindow(every: 15s, fn: mean, offset: myduration)