I’m trying to do a calculation based on the time elapsed since the last data point was recorded, something like now() - latestPoint._time
in seconds. I haven’t been able to find anything that allows you to do something like this besides elapsed() which doesn’t seem to be able to do the exact thing I’m looking for.
I was able to figure out how to calculate the time difference (see first comment) but I still don’t know how to convert it to seconds.
I mostly answered my own question. Found this page on how to calculate time difference given two time stamps. I was missing the function uint(v: {timestap})
to allow for subtracting the two times to use in difference(v: {time2} - {time1})
.
I’m still not sure how to convert this time in to seconds.
Hello @ZachElkins,
You can use the int() function:
import "regexp"
import "array"
time1 = uint(v: 2019-09-17T21:12:05Z)
time2 = uint(v: 2019-09-18T22:16:35Z)
m = duration(v: time2 - time1)
// Returns 25h4m30s
array.from(rows: [{_time: now(), _value: int(v:m)/1000000000}])
*multiplying by 1e-9 to convert from s to ns
@Anaisdg
I’m trying that right now but get error exhausting result iterator: type error @39:38-39:43: expected time but found () => A
Here is my code
import "array"
import "regexp"
import "system"
getTime = (b, me, f) => {
r = from(bucket: b)
|> range(start: -99d)
|> filter(fn: (r) =>
(r["_measurement"] == me and r["_field"] == f))
|> group(columns: ["_field"])
|> first()
|> aggregateWindow(every: 1s, fn: last, createEmpty: false)
|> yield(name: "last")
|> findColumn(fn: (key) =>
(key._field == f), column: "_time")
return r[0]
}
now = system.now()
last_data_time = getTime(b: "my_bucket", me: "my_measurement", f: "my_field")
time_since_last = duration(v: uint(v: now) - uint(v: last_data_time))
dt_seconds = array.from(rows: [{_time: now(), _value: int(v: time_since_last)}]) // This is line 39 the error is referring to
Hello @ZachElkins,
I found a couple small errors. The function you want is system.time() and I don’t think you can reassign now().
This worked for me:
import "system"
import "array"
getTime = (b, me, f) => {
r = from(bucket: b)
|> range(start: -30d)
|> filter(fn: (r) =>
(r["_measurement"] == me and r["_field"] == f))
|> group(columns: ["_field"])
|> first()
|> aggregateWindow(every: 1s, fn: last, createEmpty: false)
|> findColumn(fn: (key) => true, column: "_time")
return r[0]
}
mynow = system.time()
last_data_time = getTime(b: "noaa", me: "average_temperature", f: "degrees")
time_since_last = duration(v: uint(v: mynow) - uint(v: last_data_time))
array.from(rows: [{_time: now(), _value: uint(v: time_since_last)}])