DateTime64
允许存储时间瞬间,可以表示为日历日期和一天中的时间,具有定义的亚秒精度
Tick 大小(精度):10-precision 秒。有效范围:[ 0 : 9 ]。通常使用 - 3(毫秒)、6(微秒)、9(纳秒)。
语法
DateTime64(precision, [timezone])
在内部,数据以自 epoch 开始(1970-01-01 00:00:00 UTC)以来的 ‘ticks’ 数量作为 Int64 存储。tick 分辨率由精度参数确定。此外,DateTime64
类型可以存储时区,该时区对于整个列是相同的,这会影响 DateTime64
类型的值以文本格式显示的方式以及如何解析指定为字符串的值(‘2020-01-01 05:00:01.000’)。时区不存储在表的行(或结果集)中,而是存储在列元数据中。有关详细信息,请参阅 DateTime。
支持的值范围:[1900-01-01 00:00:00, 2299-12-31 23:59:59.99999999]
注意:最大值的精度为 8。如果使用最大精度 9 位数字(纳秒),则最大支持的值为 UTC 时间 2262-04-11 23:47:16
。
示例
- 创建具有
DateTime64
类型列的表并将数据插入其中
CREATE TABLE dt64
(
`timestamp` DateTime64(3, 'Asia/Istanbul'),
`event_id` UInt8
)
ENGINE = TinyLog;
-- Parse DateTime
-- - from integer interpreted as number of seconds since 1970-01-01.
-- - from string,
INSERT INTO dt64 VALUES (1546300800123, 1), (1546300800.123, 2), ('2019-01-01 00:00:00', 3);
SELECT * FROM dt64;
┌───────────────timestamp─┬─event_id─┐
│ 2019-01-01 03:00:00.123 │ 1 │
│ 2019-01-01 03:00:00.123 │ 2 │
│ 2019-01-01 00:00:00.000 │ 3 │
└─────────────────────────┴──────────┘
- 当将日期时间作为整数插入时,它被视为适当缩放的 Unix 时间戳 (UTC)。
1546300800000
(精度为 3)表示'2019-01-01 00:00:00'
UTC。但是,由于timestamp
列指定了Asia/Istanbul
(UTC+3) 时区,因此当作为字符串输出时,该值将显示为'2019-01-01 03:00:00'
。将日期时间作为十进制插入将以类似于整数的方式处理,不同之处在于小数点前的值是 Unix 时间戳,精确到秒,小数点后的值将被视为精度。 - 当将字符串值作为日期时间插入时,它被视为位于列时区中。
'2019-01-01 00:00:00'
将被视为位于Asia/Istanbul
时区中,并存储为1546290000000
。
- 过滤
DateTime64
值
SELECT * FROM dt64 WHERE timestamp = toDateTime64('2019-01-01 00:00:00', 3, 'Asia/Istanbul');
┌───────────────timestamp─┬─event_id─┐
│ 2019-01-01 00:00:00.000 │ 3 │
└─────────────────────────┴──────────┘
与 DateTime
不同,DateTime64
值不会自动从 String
转换。
SELECT * FROM dt64 WHERE timestamp = toDateTime64(1546300800.123, 3);
┌───────────────timestamp─┬─event_id─┐
│ 2019-01-01 03:00:00.123 │ 1 │
│ 2019-01-01 03:00:00.123 │ 2 │
└─────────────────────────┴──────────┘
与插入相反,toDateTime64
函数会将所有值视为十进制变体,因此需要在小数点后给出精度。
- 获取
DateTime64
类型值的时区
SELECT toDateTime64(now(), 3, 'Asia/Istanbul') AS column, toTypeName(column) AS x;
┌──────────────────column─┬─x──────────────────────────────┐
│ 2023-06-05 00:09:52.000 │ DateTime64(3, 'Asia/Istanbul') │
└─────────────────────────┴────────────────────────────────┘
- 时区转换
SELECT
toDateTime64(timestamp, 3, 'Europe/London') as lon_time,
toDateTime64(timestamp, 3, 'Asia/Istanbul') as istanbul_time
FROM dt64;
┌────────────────lon_time─┬───────────istanbul_time─┐
│ 2019-01-01 00:00:00.123 │ 2019-01-01 03:00:00.123 │
│ 2019-01-01 00:00:00.123 │ 2019-01-01 03:00:00.123 │
│ 2018-12-31 21:00:00.000 │ 2019-01-01 00:00:00.000 │
└─────────────────────────┴─────────────────────────┘
另请参阅