You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理NodeRed传入InfluxDB的用电数据日期并在Grafana展示图表

解决电表数据时间戳与Grafana展示问题

方案一:写入InfluxDB前修正时间戳(推荐)

从源头修正时间戳,让InfluxDB存储数据的实际所属日期,更符合时序数据库的设计逻辑,后续Grafana查询更顺畅。

1. 在Python脚本中处理

直接在生成数据的Python脚本里,将UsageDate转换为对应日期的时间戳,传给InfluxDB时指定该时间:

import json
from datetime import datetime

# 原始JSON数据
raw_data = '{"UsageDate": "2022-08-14", "Usage": 9.622}'
data = json.loads(raw_data)

# 将UsageDate转为当天结束时刻的UTC时间(也可设为0点,根据需求调整)
target_datetime = datetime.strptime(data["UsageDate"], "%Y-%m-%d").replace(hour=23, minute=59, second=59)
# 转换为InfluxDB可识别的ISO格式时间字符串
timestamp = target_datetime.isoformat() + "Z"

# 构造符合InfluxDB要求的点数据
influx_data = {
    "measurement": "electricity_usage",
    "fields": {"Usage": data["Usage"]},
    "time": timestamp
}

# 后续将influx_data传给NodeRed或直接写入InfluxDB

2. 在NodeRed中处理

如果不想修改Python脚本,可在NodeRed流程里添加函数节点,解析UsageDate并替换时间戳:

// 解析输入的JSON payload
const data = msg.payload;
// 将UsageDate转为当天23:59:59的时间对象(可调整时刻)
const targetDate = new Date(data.UsageDate);
targetDate.setHours(23, 59, 59, 0);

// 构造写入InfluxDB的格式,指定time字段
msg.payload = {
    measurement: "electricity_usage",
    fields: { Usage: data.Usage },
    time: targetDate.toISOString()
};

return msg;

之后将该节点连接到InfluxDB Out节点,确保节点配置中使用msg.payload.time作为时间戳来源。

方案二:Grafana中直接使用字符串类型的UsageDate作为X轴(应急方案)

若暂时无法修改写入逻辑,可在Grafana查询中基于字符串字段分组展示:
使用InfluxQL查询语句,按UsageDate分组聚合数据(因单日期仅一条数据,用LAST/FIRST均可):

SELECT LAST("Usage") AS "用电量" 
FROM "electricity_usage" 
WHERE $timeFilter 
GROUP BY "UsageDate" 
ORDER BY "UsageDate" ASC

然后在Grafana面板设置中:

  • X轴类型选择「类别」
  • 类别字段选择UsageDate
    即可用字符串日期作为X轴展示柱状图。

注意:此方案会浪费InfluxDB的时间索引优势,时间范围过滤灵活性较差,仅建议临时使用。

内容的提问来源于stack exchange,提问作者dw1958uk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 14:48:16