跳转到主要内容
可存储一个时间点,以日历日期和一天中的时间表示,并具有指定的子秒级精度 时间粒度 (精度) :10-precision 秒。有效范围:[ 0 : 9 ]。 通常使用 3 (毫秒) 、6 (微秒) 和 9 (纳秒) 。 语法:
DateTime64(precision, [timezone])
在内部,它将数据存储为自纪元开始 (1970-01-01 00:00:00 UTC) 以来的若干个 ‘ticks’,类型为 Int64。tick 的分辨率由 精度 参数决定。此外,DateTime64 类型还可以存储整个列统一的 时区,这会影响 DateTime64 类型的值以文本 format 显示的方式,以及将字符串形式指定的值 (‘2020-01-01 05:00:01.000’) parse 的方式。时区 不存储在表的行中 (或结果集中) ,而是存储在列元数据中。详见 DateTime 支持的值范围:[1900-01-01 00:00:00, 2299-12-31 23:59:59.999999999] 小数点后的位数取决于 精度 参数。 注意:最大值的 精度 为 8。如果使用 9 位数字 (纳秒) 的最大 精度,则 UTC 中支持的最大值为 2262-04-11 23:47:16

示例

  1. 创建一个包含 DateTime64 类型列的表,并向其中插入数据:
CREATE TABLE dt64
(
    `timestamp` DateTime64(3, 'Asia/Istanbul'),
    `event_id` UInt8
)
ENGINE = MergeTree;
-- 解析 DateTime
-- - 从整数解析,将其解释为自 1970-01-01 起的毫秒数(因精度为 3),
-- - 从小数解析,小数点前的部分表示秒数,小数点后的部分根据精度处理,
-- - 从字符串解析。

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 │
└─────────────────────────┴──────────┘
  • 以整数形式插入 datetime 时,会将其视为按相应精度缩放的 Unix 时间戳 (UTC) 。1546300800000 (精度 为 3) 表示 UTC 的 '2019-01-01 00:00:00'。但由于 timestamp 列指定了 Asia/Istanbul (UTC+3) 时区,因此在以字符串形式输出时,该值会显示为 '2019-01-01 03:00:00'。以十进制数形式插入 datetime 时,处理方式与整数类似,不同之处在于:小数点前的值是精确到秒 (含秒) 的 Unix 时间戳,小数点后的值会被视为 精度。
  • 以字符串形式插入 datetime 值时,会将其视为采用列时区。'2019-01-01 00:00:00' 会被视为采用 Asia/Istanbul 时区,并存储为 1546290000000
  1. 过滤 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 函数会将所有值都按小数处理,因此精度需要 在小数点后给出。
  1. 获取 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') │
└─────────────────────────┴────────────────────────────────┘
  1. 时区转换
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 │
└─────────────────────────┴─────────────────────────┘
另请参阅
最后修改于 2026年6月10日