InfluxDB + Flux: Get most recent timestamp for a measurement via Python API

1.5k views Asked by At

I need to get the highest (aka most recent) timestamp for a specific Measurement in InfluxDB 2.0 via the Flux query language using the Python API.

I have used the below query to get a timestamp out, but I'm unsure how to ensure that the timestamp I extract via this method is indeed the most recent one.

In particular, the indexing I use, last_data[0], is arbitrary as last_data is a list of objects like <influxdb_client.client.flux_table.FluxTable object at 0x00000193FA906AC8>, which I am unsure how to interpret. The timestamps do not seem to be sorted.

from influxdb_client import InfluxDBClient, WriteOptions

client = InfluxDBClient(url=self.influx_url, token=self.token, org=self.org_id, debug=False)

last_data = client.query_api().query(
    f'from(bucket:"{self.influx_bucket}") |> range(start: -100d) |> filter(fn: (r) => r["_measurement"] == "{devices[0]}") |> last()'
)
timestamp = last_data[0].records[0]["_stop"]
print(timestamp)
1

There are 1 answers

0
PovilasZ On BEST ANSWER

First of all, _stop is used to tell you the end of your time range. In your case, it would be just a timestamp of the query execution time as you don't enter the end date for the range. To get the timestamp for measurement you need to use _time. To get the result you want you would probably need to add |> group() before calling the last function. So it would be

last_data = client.query_api().query(
    f'from(bucket:"{self.influx_bucket}") |> range(start: -100d) |> filter(fn: (r) => r["_measurement"] == "{devices[0]}") |> group() |> last()'