Функции временных меток

Функции временных меток

Имя Описание
CURRENT_TIMESTAMP Генерирует TIMESTAMP, соответствующий времени запроса.
TIMESTAMP_TRUNC Усекает значение TIMESTAMP до заданной степени детализации.
UNIX_MICROS_TO_TIMESTAMP Преобразует количество микросекунд, прошедших с 1970-01-01 00:00:00 UTC, в TIMESTAMP.
UNIX_MILLIS_TO_TIMESTAMP Преобразует количество миллисекунд, прошедших с 1970-01-01 00:00:00 UTC, в TIMESTAMP.
UNIX_SECONDS_TO_TIMESTAMP Преобразует количество секунд, прошедших с 1970-01-01 00:00:00 UTC, в TIMESTAMP.
TIMESTAMP_ADD Добавляет временной интервал к TIMESTAMP.
TIMESTAMP_SUB Вычитает временной интервал из значения TIMESTAMP.
TIMESTAMP_TO_UNIX_MICROS Преобразует TIMESTAMP в количество микросекунд, прошедших с 1970-01-01 00:00:00 UTC.
TIMESTAMP_TO_UNIX_MILLIS Преобразует TIMESTAMP в количество миллисекунд, прошедших с 1970-01-01 00:00:00 UTC.
TIMESTAMP_TO_UNIX_SECONDS Преобразует TIMESTAMP в количество секунд, прошедших с 1970-01-01 00:00:00 UTC.
TIMESTAMP_DIFF Возвращает целое число указанных интервалов unit между двумя значениями TIMESTAMP.
TIMESTAMP_EXTRACT Извлекает определенную часть part (например, год, месяц, день) из значения TIMESTAMP.

CURRENT_TIMESTAMP

Синтаксис:

current_timestamp() -> TIMESTAMP

Описание.

Возвращает временную метку начала запроса input (в микросекундах с 1970-01-01 00:00:00 UTC).

Это значение стабильно в рамках запроса и всегда будет разрешаться в одно и то же значение при многократном вызове.

TIMESTAMP_TRUNC

Синтаксис:

timestamp_trunc(timestamp: TIMESTAMP | BSON_TIMESTAMP, granularity: STRING[, timezone: STRING]) -> TIMESTAMP

Описание.

Усекает временную метку до заданной детализации.

Аргумент granularity должен быть строкой и иметь одно из следующих значений:

  • microsecond
  • millisecond
  • second
  • minute
  • hour
  • day
  • week
  • week([weekday])
  • month
  • quarter
  • year
  • isoyear

Если указан аргумент timezone, усечение будет выполняться на основе календарных границ заданного часового пояса (например, усечение дня будет выполняться до полуночи в заданном часовом поясе). При усечении будет учитываться переход на летнее время.

Если параметр timezone не указан, усечение будет выполняться на основе календарных границ UTC.

Аргумент timezone должен быть строковым представлением часового пояса из базы данных tz, например America/New_York. Вы также можете задать собственное смещение по времени, указав смещение от GMT.

Примеры

timestamp granularity timezone timestamp_trunc(timestamp, granularity, timezone)
2000-01-01 10:20:30:123456 UTC "second" Не предусмотрено 2001-01-01 10:20:30 UTC
31.05.1997 04:30:30 UTC "day" Не предусмотрено 31 мая 1997 г., 00:00:00 UTC
31.05.1997 04:30:30 UTC "day" "America/Los_Angeles" 30 мая 1997 г., 07:00:00 UTC
16.03.2001 04:00:00 UTC "week(friday) Не предусмотрено 16.03.2001 00:00:00 UTC
23.03.2001 04:00:00 UTC "week(friday) "America/Los_Angeles" 23.03.2001 17:00:00 UTC
24 января 2026 г., 20:00:00 по всемирному координированному времени (UTC) "month" "GMT+06:32:43" 2026-01-01T06:32:43 UTC

UNIX_MICROS_TO_TIMESTAMP

Синтаксис:

unix_micros_to_timestamp(input: INT64) -> TIMESTAMP

Описание.

Преобразует input (интерпретируется как количество микросекунд с 1970-01-01 00:00:00 UTC) в TIMESTAMP. Возвращает error, если input не может быть преобразовано в допустимое значение TIMESTAMP.

Примеры

input unix_micros_to_timestamp(input)
0 л 01.01.1970 00:00:00 UTC
400123456L 1970-01-01 00:06:40.123456 UTC
-1000000L 31.12.1969 23:59:59 UTC
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("createdAtMicros").unixMicrosToTimestamp().as("createdAtString")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("createdAtMicros").unixMicrosToTimestamp().as("createdAtString")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("createdAtMicros").unixMicrosToTimestamp().as("createdAtString")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAtMicros").unixMicrosToTimestamp().alias("createdAtString")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAtMicros").unixMicrosToTimestamp().alias("createdAtString")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("documents")
    .select(
        Field.of("createdAtMicros")
        .unix_micros_to_timestamp()
        .as_("createdAtString")
    )
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("documents")
        .select(unixMicrosToTimestamp(field("createdAtMicros")).as("createdAtString"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.UnixMicrosToTimestamp(firestore.FieldOf("createdAtMicros")).As("createdAtString"),
	)).
	Execute(ctx)

UNIX_MILLIS_TO_TIMESTAMP

Синтаксис:

unix_millis_to_timestamp(input: INT64) -> TIMESTAMP

Описание.

Преобразует input (количество миллисекунд, прошедших с 1970-01-01 00:00:00 UTC) в TIMESTAMP. Возвращает error, если input не может быть преобразовано в допустимое значение TIMESTAMP.

Примеры

input unix_millis_to_timestamp(input)
0 л 01.01.1970 00:00:00 UTC
4000123L 1970-01-01 01:06:40.123 UTC
-1000000L 31.12.1969 23:43:20 UTC
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("createdAtMillis").unixMillisToTimestamp().as("createdAtString")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("createdAtMillis").unixMillisToTimestamp().as("createdAtString")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("createdAtMillis").unixMillisToTimestamp().as("createdAtString")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAtMillis").unixMillisToTimestamp().alias("createdAtString")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAtMillis").unixMillisToTimestamp().alias("createdAtString")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("documents")
    .select(
        Field.of("createdAtMillis")
        .unix_millis_to_timestamp()
        .as_("createdAtString")
    )
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("documents")
        .select(unixMillisToTimestamp(field("createdAtMillis")).as("createdAtString"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.UnixMillisToTimestamp(firestore.FieldOf("createdAtMillis")).As("createdAtString"),
	)).
	Execute(ctx)

UNIX_SECONDS_TO_TIMESTAMP

Синтаксис:

unix_seconds_to_timestamp(input: INT64) -> TIMESTAMP

Описание.

Преобразует input (интерпретируется как количество секунд, прошедших с 1970-01-01 00:00:00 UTC) в TIMESTAMP. Возвращает error, если input не может быть преобразовано в допустимое значение TIMESTAMP.

Примеры

input unix_seconds_to_timestamp(input)
0 л 01.01.1970 00:00:00 UTC
60 л 1970-01-01 00:01:00 UTC
-300L 31.12.1969 23:55:00 UTC
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("createdAtSeconds").unixSecondsToTimestamp().as("createdAtString")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("createdAtSeconds").unixSecondsToTimestamp().as("createdAtString")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("createdAtSeconds").unixSecondsToTimestamp().as("createdAtString")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAtSeconds").unixSecondsToTimestamp().alias("createdAtString")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAtSeconds").unixSecondsToTimestamp().alias("createdAtString")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("documents")
    .select(
        Field.of("createdAtSeconds")
        .unix_seconds_to_timestamp()
        .as_("createdAtString")
    )
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("documents")
        .select(unixSecondsToTimestamp(field("createdAtSeconds")).as("createdAtString"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.UnixSecondsToTimestamp(firestore.FieldOf("createdAtSeconds")).As("createdAtString"),
	)).
	Execute(ctx)

TIMESTAMP_ADD

Синтаксис:

timestamp_add(timestamp: TIMESTAMP | BSON_TIMESTAMP, unit: STRING, amount: INT64) -> TIMESTAMP

Описание.

Добавляет amount unit из timestamp. Аргумент amount может быть отрицательным. В этом случае он эквивалентен TIMESTAMP_SUB.

Аргумент unit должен быть строкой и иметь одно из следующих значений:

  • microsecond
  • millisecond
  • second
  • minute
  • hour
  • day

Если полученная временная метка не укладывается в диапазон TIMESTAMP, выдается ошибка.

Примеры

timestamp unit amount timestamp_add(timestamp, unit, amount)
20.02.2025 00:00:00 UTC "minute" 2L 20.02.2025 00:02:00 UTC
20.02.2025 00:00:00 UTC "час" -4L 19.02.2025 20:00:00 UTC
20.02.2025 00:00:00 UTC "day" 5L 25.02.2025 00:00:00 UTC
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("createdAt").timestampAdd("day", 3653).as("expiresAt")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("createdAt").timestampAdd("day", 3653).as("expiresAt")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("createdAt").timestampAdd(3653, .day).as("expiresAt")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAt")
          .timestampAdd("day", 3653)
          .alias("expiresAt")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAt").timestampAdd("day", 3653).alias("expiresAt")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("documents")
    .select(Field.of("createdAt").timestamp_add("day", 3653).as_("expiresAt"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("documents")
        .select(timestampAdd(field("createdAt"), "day", 3653).as("expiresAt"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.TimestampAdd(firestore.FieldOf("createdAt"), "day", 3653).As("expiresAt"),
	)).
	Execute(ctx)

TIMESTAMP_SUB

Синтаксис:

timestamp_sub(timestamp: TIMESTAMP | BSON_TIMESTAMP, unit: STRING, amount: INT64) -> TIMESTAMP

Описание.

Вычитает amount unit из timestamp. Аргумент amount может быть отрицательным. В этом случае он эквивалентен TIMESTAMP_ADD.

Аргумент unit должен быть строкой и иметь одно из следующих значений:

  • microsecond
  • millisecond
  • second
  • minute
  • hour
  • day

Если полученная временная метка не укладывается в диапазон TIMESTAMP, выдается ошибка.

Примеры

timestamp unit amount timestamp_sub(timestamp, unit, amount)
4 июля 2026 г., 00:00:00 UTC "minute" 40L 03.07.2026 23:20:00 UTC
4 июля 2026 г., 00:00:00 UTC "час" -24L 5 июля 2026 г., 00:00:00 UTC
4 июля 2026 г., 00:00:00 UTC "day" 3L 01.07.2026 00:00:00 UTC
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("expiresAt").timestampSubtract("day", 14).as("sendWarningTimestamp")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("expiresAt").timestampSubtract("day", 14).as("sendWarningTimestamp")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("expiresAt").timestampSubtract(14, .day).as("sendWarningTimestamp")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("documents")
    .select(
        field("expiresAt")
          .timestampSubtract("day", 14)
          .alias("sendWarningTimestamp")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("documents")
    .select(
        field("expiresAt").timestampSubtract("day", 14).alias("sendWarningTimestamp")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("documents")
    .select(
        Field.of("expiresAt")
        .timestamp_subtract("day", 14)
        .as_("sendWarningTimestamp")
    )
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("documents")
        .select(timestampSubtract(field("expiresAt"), "day", 14).as("sendWarningTimestamp"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.TimestampSubtract(firestore.FieldOf("expiresAt"), "day", 14).As("sendWarningTimestamp"),
	)).
	Execute(ctx)

TIMESTAMP_TO_UNIX_MICROS

Синтаксис:

timestamp_to_unix_micros(input: TIMESTAMP | BSON_TIMESTAMP) -> INT64

Описание.

Преобразует input в количество микросекунд, прошедших с 1970-01-01 00:00:00 UTC. Усекает более высокие уровни точности, округляя до начала микросекунды.

Примеры

input timestamp_to_unix_micros(input)
01.01.1970 00:00:00 UTC 0 л
1970-01-01 00:06:40.123456 UTC 400123456L
31.12.1969 23:59:59 UTC -1000000L
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixMicros().as("unixMicros")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixMicros().as("unixMicros")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("dateString").timestampToUnixMicros().as("unixMicros")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("documents")
    .select(
        field("dateString").timestampToUnixMicros().alias("unixMicros")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("documents")
    .select(
        field("dateString").timestampToUnixMicros().alias("unixMicros")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("documents")
    .select(Field.of("dateString").timestamp_to_unix_micros().as_("unixMicros"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("documents")
        .select(timestampToUnixMicros(field("dateString")).as("unixMicros"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.TimestampToUnixMicros(firestore.FieldOf("dateString")).As("unixMicros"),
	)).
	Execute(ctx)

TIMESTAMP_TO_UNIX_MILLIS

Синтаксис:

timestamp_to_unix_millis(input: TIMESTAMP | BSON_TIMESTAMP) -> INT64

Описание.

Преобразует input в количество миллисекунд, прошедших с 1970-01-01 00:00:00 UTC. Округляет значения до миллисекунд.

Примеры

input timestamp_to_unix_millis(input)
01.01.1970 00:00:00 UTC 0 л
1970-01-01 01:06:40.123 UTC 4000123L
1969-12-31 23:43:20 -1000000L
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixMillis().as("unixMillis")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixMillis().as("unixMillis")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("dateString").timestampToUnixMillis().as("unixMillis")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("documents")
    .select(
        field("dateString").timestampToUnixMillis().alias("unixMillis")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("documents")
    .select(
        field("dateString").timestampToUnixMillis().alias("unixMillis")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("documents")
    .select(Field.of("dateString").timestamp_to_unix_millis().as_("unixMillis"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("documents")
        .select(timestampToUnixMillis(field("dateString")).as("unixMillis"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.TimestampToUnixMillis(firestore.FieldOf("dateString")).As("unixMillis"),
	)).
	Execute(ctx)

TIMESTAMP_TO_UNIX_SECONDS

Синтаксис:

timestamp_to_unix_seconds(input: TIMESTAMP | BSON_TIMESTAMP) -> INT64

Описание.

Преобразует input в количество секунд, прошедших с 1970-01-01 00:00:00 UTC. Округляет значение до секунды в меньшую сторону.

Примеры

input timestamp_to_unix_seconds(input)
01.01.1970 00:00:00 UTC 0 л
1970-01-01 00:01:00 UTC 60 л
31.12.1969 23:55:00 UTC -300L
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixSeconds().as("unixSeconds")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixSeconds().as("unixSeconds")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("dateString").timestampToUnixSeconds().as("unixSeconds")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("documents")
    .select(
        field("dateString").timestampToUnixSeconds().alias("unixSeconds")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("documents")
    .select(
        field("dateString").timestampToUnixSeconds().alias("unixSeconds")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("documents")
    .select(Field.of("dateString").timestamp_to_unix_seconds().as_("unixSeconds"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("documents")
        .select(timestampToUnixSeconds(field("dateString")).as("unixSeconds"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.TimestampToUnixSeconds(firestore.FieldOf("dateString")).As("unixSeconds"),
	)).
	Execute(ctx)

TIMESTAMP_DIFF

Синтаксис:

timestamp_diff(end: TIMESTAMP | BSON_TIMESTAMP, start: TIMESTAMP | BSON_TIMESTAMP, unit: STRING) -> INT64

Описание.

Возвращает целое число указанных интервалов unit между двумя значениями TIMESTAMP.

  • Возвращает отрицательное значение, если end предшествует start.
  • Усекает дробную часть. Например, timestamp_diff("2021-01-01 00:00:01", "2021-01-01 00:00:00", "minute") возвращает 0.

Аргумент unit должен быть строкой и иметь одно из следующих значений:

  • microsecond
  • millisecond
  • second
  • minute
  • hour
  • day

Примеры

end start unit timestamp_diff(end, start, unit)
2026-07-04 00:01:00 UTC 4 июля 2026 г., 00:00:00 UTC "second" 60 л
4 июля 2026 г., 00:00:00 UTC 5 июля 2026 г., 00:00:00 UTC "day" -1L
04.07.2026 00:00:59 UTC 4 июля 2026 г., 00:00:00 UTC "minute" 0 л

TIMESTAMP_EXTRACT

Синтаксис:

timestamp_extract(timestamp: TIMESTAMP | BSON_TIMESTAMP, part: STRING[, timezone: STRING]) -> INT64

Описание.

Извлекает определенную часть part (например, год, месяц, день) из timestamp.

Аргумент part должен быть строкой и иметь одно из следующих значений:

  • microsecond
  • millisecond
  • second
  • minute
  • hour
  • day
  • dayofweek – возвращает значение от 1 (воскресенье) до 7 (суббота).
  • dayofyear
  • week – возвращает номер недели в году, начиная с 1 для первого воскресенья года.
  • week([weekday]): возвращает номер недели в году, начиная с указанного дня недели weekday.
  • month
  • quarter
  • year
  • isoweek – возвращает номер недели по стандарту ISO 8601.
  • isoyear: возвращает год по стандарту ISO 8601.

Если указан аргумент timezone, извлечение будет основано на календаре заданного часового пояса. При извлечении будет учитываться переход на летнее время.

Если не указать timezone, извлечение будет основано на UTC.

Аргумент timezone должен быть строковым представлением часового пояса из базы данных часовых поясов, например America/New_York. Вы также можете задать собственное смещение по времени, указав смещение от GMT.

Примеры

timestamp part timezone timestamp_extract(timestamp, part, timezone)
20.02.2025 10:20:30 UTC "year" Не предусмотрено 2025 г.
20.02.2025 10:20:30 UTC "day" Не предусмотрено 20
31.12.2025 23:59:59 UTC "year" "Asia/Tokyo" 2026