日期和时间作为 Postgres 中的 UTC 时间戳

Date and time as UTC timestamp in Postgres

我的 table 中有日期和时间字段。两者均以本地服务器时间设置。 是否可以将两个字段都转换为单个 UTC ISO 时间戳?

只需添加两个:

SELECT date_col + time_col AS timestamp_col

类型 timestamp [without time zone] 无论如何在内部存储为 UTC 时间戳。只有显示会根据您的会话的时区设置进行调整。如果需要将时间戳显示为 UTC 时间戳,请使用 AT TIME ZONE 结构:

SELECT timestamp_col AT TIME ZONE 'UTC';

请注意,此 returns 应用于 timestamptimestamp with time zone
详细信息:

  • Ignoring timezones altogether in Rails and PostgreSQL

例如,要在莫斯科将时间戳显示为 timestamptz

SELECT (date_col + time_col) AT TIME ZONE 'Europe/Moscow' AS tstz_col