使用 InfluxQL 从 InfluxDB 的时间字段中提取日期或小时

问题描述 投票:0回答:1

我想从 InfluxDB 中的时间戳字段中提取日期的部分内容,例如小时、日、月等。这将有助于在 Grafana 中创建热图。

目标状态:

时间 小时
2024-01-02 04:25:00 2 1 4
2023-12-25 16:25:00 25 12 16

我必须使用 InfluxQL,所以 Flux 或 SQL 不是一个选项。

  • date_part
    是理想的选择,但仅在 Flux 或 SQL 中可用
  • InfluxQL 中似乎不存在日期修改功能

我考虑过但尚未弄清楚的选项:手动计算或字符串操作,因此指针会很有帮助。

influxdb influxql
1个回答
0
投票

不幸的是,在 InfluxDB 的查询语言 InfluxQL 中,不直接支持日期部分提取。这是 InfluxQL 的限制,目前没有内置函数可以从时间戳中提取小时、分钟或日期。

作为解决方法,您可以导出数据并使用可处理日期和时间操作的编程语言(例如

Python
JavaScript
)处理时间戳。提取所需部分后,您可以将它们作为新字段添加到数据中并将其导入回 InfluxDB。

解决方法涉及导出和导入数据。

在Python中,您可以将InfluxDB时间戳转换为日期时间对象,然后提取所需的部分。这是一个简单的例子:

from datetime import datetime, timezone

# Assuming `ts` is your timestamp from InfluxDB
ts = 1578152602608558363

# Convert the timestamp to a datetime object
dt = datetime.fromtimestamp(ts / 1e9, timezone.utc)

# Extract the parts
day = dt.day
month = dt.month
hour = dt.hour
© www.soinside.com 2019 - 2024. All rights reserved.