postgresql - UTC 中的日期和时间 - 如何将它们存储在 postgres 中?

标签 postgresql date time timestamp timestamp-with-timezone

我正在获取我的数据:UTC 日期和时间,在单独列中的 csv 文件格式中。因为我需要将这个区域转换为我居住地的日期和时间,目前在夏天转换为 UTC+2,也许还有其他一些区域我想知道在我们谈论时在 postgres 中插入数据的最佳实践是什么数据类型。我应该将我的两个数据放在一个列中还是将它们按类型分开:日期和时间,如果不是,我应该使用 timestamp 或 timestampz(或其他东西)。

最佳答案

使用 timestamptz 它将以 UTC 格式存储您的时间戳。并将根据其语言环境将其显示给客户端。

https://www.postgresql.org/docs/current/static/datatype-datetime.html

For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system's TimeZone parameter, and is converted to UTC using the offset for the timezone zone.

When a timestamp with time zone value is output, it is always converted from UTC to the current timezone zone, and displayed as local time in that zone. To see the time in another time zone, either change timezone or use the AT TIME ZONE construct (see Section 9.9.3).

更新 Lukasz 的另一个好点,我不得不提到:

Also in favor of single column is the fact that if you would store both date and time in separate columns you would still need to combine them and convert to timestamp if you wanted to change time zone of date.

不这样做会导致日期“2017-12-31”和时间“23:01:01”在其他时区实际上不仅是不同的时间,而且是不同的日期,所有 YEAR、MONTH 和 DAY 都不同

另一个更新 根据 Laurenz 通知,不要忘记上面的文档引用 使用该时区的适当偏移量将具有明确指定时区的输入值转换为 UTC。这意味着您必须仔细管理输入日期。例如:

t=# create table t(t timestamptz);
CREATE TABLE
t=# set timezone to 'GMT+5';
SET
t=# insert into t select '2017-01-01 00:00:00';
INSERT 0 1
t=# insert into t select '2017-01-01 00:00:00' at time zone 'UTC';
INSERT 0 1
t=# insert into t select '2017-01-01 00:00:00+02';
INSERT 0 1
t=# select * from t;
           t
------------------------
 2017-01-01 00:00:00-05
 2017-01-01 05:00:00-05
 2016-12-31 17:00:00-05
(3 rows)

关于postgresql - UTC 中的日期和时间 - 如何将它们存储在 postgres 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44432682/

相关文章:

Windows 和 Linux 中的 PHP 日期函数

mysql - 确定日期的月份是否属于日期的四分之一

java - 将当前时间(以毫秒为单位)与共享首选项中保存的时间进行比较

mysql - SQL 模式创建(头脑 Storm 有帮助吗?)

java - 根据特定列将 Postgresql 行与 Mongodb 文档连接起来

postgresql - 从 Postgres 中的 JSONB 提取多个值

javascript - Twitter 风格的前一段时间格式化 ("2h")与 Javascript

ruby - 使用 Ruby(没有 Rails)在 Heroku 中创建 Postgresql 数据库

regex - 文本编辑器(正则表达式?)解释日期字符串的技巧

javascript - 计算剩余下载时间