#!/usr/bin/env python # coding: utf-8 # https://influxdb-client.readthedocs.io/en/latest/usage.html#id4 # # or generate source code from Web UI: `Load Data` -> `Source` # # ## Query # Flux: https://docs.influxdata.com/influxdb/v2.0/query-data/flux/query-fields/ # In[1]: import re, os path = '/data/conf/init.sh' # influxdb_token=... (optional) if os.path.exists(path): with open(path,'r',encoding='utf-8') as f: content = f.read() token = re.search("(?<=influxdb_token=).*", content).group(0) else: token = input("influxdb_token=") from influxdb_client import InfluxDBClient client = InfluxDBClient(url="http://192.168.88.21:8086", token=token, org="ferro") query_api = client.query_api() # In[2]: import pandas as pd query=''' from(bucket: "home") |> range(start: -3d) |> filter(fn: (r) => r["_measurement"] == "度数") |> filter(fn: (r) => r["_field"] == "当前") |> filter(fn: (r) => r["tag"] == "203" or r["tag"] == "205" ) |> keep(columns: ["_time", "_value", "tag"]) ''' query = ''.join([ line for line in query.splitlines() if not line.startswith('#') ]) df = client.query_api().query_data_frame(query=query).drop(['result', 'table'], axis=1) df['_time'] = pd.to_datetime(df['_time'], format='%Y-%m-%d %H:%M:%S.%f%z') # https://strftime.org/ df['tag'] = df['tag'].astype('string') df['diff_value'] = df.groupby(['tag'])['_value'].diff().fillna(0) df['diff_time'] = df.groupby(['tag'])['_time'].diff() # In[3]: df.dtypes # In[4]: df_last = df.groupby(['tag']).last() df_last # In[5]: df_result = df[df.diff_time.notnull()] df_result