处理时间类型
A 时间 类型表示一个具有纳秒精度的单一时间点。
类型名称: time
时间语法
时间文字通过 RFC3339 时间戳 表示。
YYYY-MM-DD
YYYY-MM-DDT00:00:00Z
YYYY-MM-DDT00:00:00.000Z
将数据类型转换为时间
- string: 解析为 RFC3339 时间戳 并转换为时间值。
- int: 被解析为Unix纳秒时间戳并转换为时间值。
- uint: 解析为Unix纳秒时间戳并转换为时间值。
time(v: "2021-01-01")
// Returns 2021-01-01T00:00:00.000000000Z
time(v: 1609459200000000000)
// Returns 2021-01-01T00:00:00.000000000Z
time(v: uint(v: 1609459200000000000))
// Returns 2021-01-01T00:00:00.000000000Z
将列转换为时间
Flux 使您能够在表的流中迭代行并将列转换为时间。
将 _value 列转换为时间,使用 toTime() 函数。
toTime() 仅作用于 _value 列。
data
|> toTime()
给定以下输入数据:
| _时间 | _值 (int) |
|---|---|
| 2021-01-01T00:00:00Z | 10000000000 |
| 2021-01-01T02:00:00Z | 20000000000 |
| 2021-01-01T03:00:00Z | 30000000000 |
| 2021-01-01T04:00:00Z | 40000000000 |
上面的例子返回:
| _时间 | _值 (时间) |
|---|---|
| 2021-01-01T00:00:00Z | 1970-01-01T00:00:10Z |
| 2021-01-01T02:00:00Z | 1970-01-01T00:00:20Z |
| 2021-01-01T03:00:00Z | 1970-01-01T00:00:30Z |
| 2021-01-01T04:00:00Z | 1970-01-01T00:00:40Z |
将任何列转换为时间:
data
|> map(fn: (r) => ({ r with epoch_ns: time(v: r.epoch_ns) }))
给定以下输入数据:
| 时间 | 时间戳纳秒 (int) |
|---|---|
| 2021-01-01T00:00:00Z | 10000000000 |
| 2021-01-01T02:00:00Z | 20000000000 |
| 2021年01月01日03:00:00Z | 30000000000 |
| 2021-01-01T04:00:00Z | 40000000000 |
上面的例子返回:
| _时间 | epoch_ns (时间) |
|---|---|
| 2021-01-01T00:00:00Z | 1970-01-01T00:00:10Z |
| 2021-01-01T02:00:00Z | 1970-01-01T00:00:20Z |
| 2021-01-01T03:00:00Z | 1970-01-01T00:00:30Z |
| 2021-01-01T04:00:00Z | 1970-01-01T00:00:40Z |
操作时间
将时间戳截断到指定单位
截断时间戳在规范化不规则时间戳时很有帮助。 要将时间戳截断为指定单位:
- 导入
date包。 - 使用
date.truncate(),并提供要截断的时间单位。
截断到周
当将时间值截断到周时 (1w),周是使用Unix元年 (1970-01-01T00:00:00Z UTC)来确定的。Unix元年是在星期四,因此所有计算出的周都是从星期四开始。
t0 = 2021-01-08T14:54:10.023849Z
date.truncate(t: t0, unit: 1ms)
// Returns 2021-01-08T14:54:10.023000000Z
date.truncate(t: t0, unit: 1m)
// Returns 2021-01-08T14:54:00.000000000Z
date.truncate(t: t0, unit: 1w)
// Returns 2021-01-07T00:00:00.000000000Z
date.truncate(t: t0, unit: 1mo)
// Returns 2021-01-01T00:00:00.000000000Z
要截断 _time 列,使用 truncateTimeColumn():
data
|> truncateTimeColumn(unit: 1m)
给定以下输入数据:
| 时间 | 值 |
|---|---|
| 2021-01-01T00:00:33Z | 1.0 |
| 2021-01-01T00:01:10Z | 1.1 |
| 2021-01-01T00:02:45Z | 3.6 |
| 2021-01-01T00:03:23Z | 2.5 |
上面的例子返回:
| 时间 | 值 |
|---|---|
| 2021-01-01T00:00:00Z | 1.0 |
| 2021-01-01T00:01:00Z | 1.1 |
| 2021-01-01T00:02:00Z | 3.6 |
| 2021-01-01T00:03:00Z | 2.5 |
从时间戳解析时间单位
从时间值中解析特定的时间单位:
- 导入
date包。 - 使用
date包中的函数从时间戳返回特定的时间单位。
import "date"
t0 = 2021-01-08T14:54:10.023849Z
date.minute(t: t0)
// Returns 54
date.year(t: t0)
// Returns 2021
date.quarter(t: t0)
// Returns 1
将持续时间添加到时间值
要将一个 duration 添加到时间值中:
- 导入
date包。 - 使用
date.add()为时间值添加持续时间。
import "date"
date.add(d: 1w, to: 2021-01-01T00:00:00Z)
// Returns 2021-01-08T00:00:00.000000000Z
从时间值中减去一个持续时间
要从时间值中减去一个 duration:
- 导入
date包。 - 使用
date.sub()从一个时间值中减去一个持续时间。
import "date"
date.sub(d: 1w, from: 2021-01-01T00:00:00Z)
// Returns 2020-12-25T00:00:00.000000000Z