Help wanted!

The following content of this documentation page has been machine-translated. But unlike other websites, it is not done on the fly. This translated text lives on GitHub repository alongside main ClickHouse codebase and waits for fellow native speakers to make it more human-readable. You can also use the original English version as a reference.

Help ClickHouse documentation by editing this page

Datetime64

此类型允许以日期(date)加时间(time)的形式来存储一个时刻的时间值,具有定义的亚秒精度

时间刻度大小(精度):10-精度 秒

语法:

  1. DateTime64(precision, [timezone])

在内部,此类型以Int64类型将数据存储为自Linux纪元开始(1970-01-01 00:00:00UTC)的时间刻度数(ticks)。时间刻度的分辨率由precision参数确定。此外,DateTime64 类型可以像存储其他数据列一样存储时区信息,时区会影响 DateTime64 类型的值如何以文本格式显示,以及如何解析以字符串形式指定的时间数据 (‘2020-01-01 05:00:01.000’)。时区不存储在表的行中(也不在resultset中),而是存储在列的元数据中。详细信息请参考 DateTime 数据类型.

示例

1. 创建一个具有 DateTime64 类型列的表,并向其中插入数据:

  1. CREATE TABLE dt
  2. (
  3. `timestamp` DateTime64(3, 'Europe/Moscow'),
  4. `event_id` UInt8
  5. )
  6. ENGINE = TinyLog
  1. INSERT INTO dt Values (1546300800000, 1), ('2019-01-01 00:00:00', 2)
  1. SELECT * FROM dt
  1. ┌───────────────timestamp─┬─event_id─┐
  2. 2019-01-01 03:00:00.000 1
  3. 2019-01-01 00:00:00.000 2
  4. └─────────────────────────┴──────────┘
  • 将日期时间作为integer类型插入时,它会被视为适当缩放的Unix时间戳(UTC)。1546300800000 (精度为3)表示 '2019-01-01 00:00:00' UTC. 不过,因为 timestamp 列指定了 Europe/Moscow (UTC+3)的时区,当作为字符串输出时,它将显示为 '2019-01-01 03:00:00'
  • 当把字符串作为日期时间插入时,它会被赋予时区信息。 '2019-01-01 00:00:00' 将被认为处于 Europe/Moscow 时区并被存储为 1546290000000.

2. 过滤 DateTime64 类型的值

  1. SELECT * FROM dt WHERE timestamp = toDateTime64('2019-01-01 00:00:00', 3, 'Europe/Moscow')
  1. ┌───────────────timestamp─┬─event_id─┐
  2. 2019-01-01 00:00:00.000 2
  3. └─────────────────────────┴──────────┘

DateTime 不同, DateTime64 类型的值不会自动从 String 类型的值转换过来

3. 获取 DateTime64 类型值的时区信息:

  1. SELECT toDateTime64(now(), 3, 'Europe/Moscow') AS column, toTypeName(column) AS x
  1. ┌──────────────────column─┬─x──────────────────────────────┐
  2. 2019-10-16 04:12:04.000 DateTime64(3, 'Europe/Moscow')
  3. └─────────────────────────┴────────────────────────────────┘

4. 时区转换

  1. SELECT
  2. toDateTime64(timestamp, 3, 'Europe/London') as lon_time,
  3. toDateTime64(timestamp, 3, 'Europe/Moscow') as mos_time
  4. FROM dt
  1. ┌───────────────lon_time──┬────────────────mos_time─┐
  2. 2019-01-01 00:00:00.000 2019-01-01 03:00:00.000
  3. 2018-12-31 21:00:00.000 2019-01-01 00:00:00.000
  4. └─────────────────────────┴─────────────────────────┘

另请参阅