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

如何在Prometheus查询中使用Grafana时间范围并生成Excel报表?

问题解答

一、Grafana中使用时间范围变量构建查询

Grafana内置了多个与时间范围绑定的变量,可直接在PromQL查询中引用,完美适配你依赖右上角选定时间范围的需求:

  • $__range:代表当前选中时间范围的时长(比如选3小时就是3h,选1天就是1d)
  • $__timeFrom:选中时间范围的起始Unix时间戳
  • $__timeTo:选中时间范围的结束Unix时间戳
  • $__interval:Grafana根据时间范围自动计算的查询间隔,适合绘制趋势类图表

如果要查询选定时间范围内的总请求数,推荐用以下PromQL写法:

sum(increase(http_requests_total[$__range]))

解释:increase函数会自动处理计数器重置,计算指标在指定时间范围内的增量(即这段时间的总请求数),sum用于聚合所有实例或维度的请求数据。

二、Python脚本调用Prometheus查询时间范围并生成Excel报表

步骤1:安装依赖库

先安装所需的工具包:

pip install requests pandas openpyxl

步骤2:实现完整脚本

以下是可直接复用的示例脚本,包含时间格式转换、Prometheus API调用、数据处理及Excel生成:

import requests
import pandas as pd
from datetime import datetime

# 替换为你的Prometheus实例地址
PROMETHEUS_ADDR = "http://your-prometheus-host:9090"

def str_to_timestamp(time_str):
    # 将"YYYY-MM-DD HH:MM:SS"格式的字符串转为Unix时间戳(秒级)
    dt = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
    return int(dt.timestamp())

def fetch_prom_data(query, start_time, end_time):
    start_ts = str_to_timestamp(start_time)
    end_ts = str_to_timestamp(end_time)
    
    # 调用Prometheus的query_range接口获取时间序列数据
    params = {
        "query": query,
        "start": start_ts,
        "end": end_ts,
        "step": "1m"  # 数据点间隔,可根据需求调整(如5m、1h)
    }
    resp = requests.get(f"{PROMETHEUS_ADDR}/api/v1/query_range", params=params)
    resp.raise_for_status()  # 捕获请求异常
    return resp.json()

def export_to_excel(data, output_path):
    # 解析Prometheus返回的JSON数据,转为DataFrame
    result_list = data["data"]["result"]
    rows = []
    for item in result_list:
        labels = item["metric"]
        for ts, val in item["values"]:
            # 将Unix时间戳转回可读格式
            readable_time = datetime.fromtimestamp(int(ts)).strftime("%Y-%m-%d %H:%M:%S")
            rows.append({
                "时间": readable_time,
                **labels,
                "数值": float(val)
            })
    df = pd.DataFrame(rows)
    
    # 保存为Excel文件
    df.to_excel(output_path, index=False, engine="openpyxl")
    print(f"报表已生成:{output_path}")

if __name__ == "__main__":
    # 示例:查询2023-02-20 6:00至9:00的请求数趋势
    target_query = "rate(http_requests_total[1m])"  # 可替换为sum(increase(http_requests_total[3h]))查询总请求数
    start = "2023-02-20 6:00:00"
    end = "2023-02-20 9:00:00"
    output_file = "prometheus_request_report.xlsx"
    
    prom_data = fetch_prom_data(target_query, start, end)
    export_to_excel(prom_data, output_file)

关键说明:

  • 若只需查询整个时间范围的总请求数而非趋势,可将target_query改为sum(increase(http_requests_total[3h])),并改用Prometheus的/api/v1/query接口(只需传入time参数为结束时间戳)。
  • step参数决定返回数据点的密度,3小时范围用1分钟步长会生成180个数据点,可根据报表需求调整。
  • Prometheus返回的value为字符串类型,需转换为数值后再写入Excel。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:02:43