postgresql Now() 没有时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20812091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:33:21  来源:igfitidea点击:

Now() without timezone

postgresqltimestamppostgresql-9.2

提问by アレックス

I have a column added_atof type timestamp without time zone. I want it's default value to be the current date-time but without time zone. The function now()returns a timezone as well.

我有一个added_at类型的列timestamp without time zone。我希望它的默认值是当前日期时间但没有时区。该函数也now()返回一个时区。

How do I solve that problem?

我该如何解决这个问题?

回答by Erwin Brandstetter

SELECT now()::timestamp

That's all. The cast converts the timestamp to the current timestamp of your time zone. That's also how the standard SQL function LOCALTIMESTAMPis implemented in Postgres.

就这样。演员表将时间戳转换为您所在时区的当前时间戳。这也是标准 SQL 函数LOCALTIMESTAMP在 Postgres 中的实现方式。

If you don't operate in multiple time zones, that works just fine. Else switch to timestamptzfor added_at. The difference?

如果您不在多个时区操作,那效果很好。否则切换到timestamptzfor added_at。区别?

回答by Richard Huxton

Well you can do something like:

好吧,您可以执行以下操作:

SELECT now() AT TIME ZONE current_setting('TimeZone');
SELECT now() AT TIME ZONE 'Europe/Paris';
SELECT now() AT TIME ZONE 'UTC';

Not sure how that makes any sense for a column "added_at". You almost always want an absolute timestamp (timestamp with time zone) not a floating one.

不确定这对“ added_at”列有何意义。您几乎总是想要一个绝对时间戳(带时区的时间戳)而不是浮动时间戳。



Edit responding to points below:

编辑回应以下几点:

  1. Yes, should use timestamp with time zone (absolute time) unless you have a good reason not to.

  2. The client timezone is given by SHOW TimeZoneor current_setting(...)as shown above.

  1. 是的,除非您有充分的理由不这样做,否则应该使用带时区(绝对时间)的时间戳。

  2. 客户端时区由SHOW TimeZone或给出,current_setting(...)如上所示。

Do take some time to skim the manuals - they cover all this quite well.

一定要花一些时间浏览手册——它们很好地涵盖了所有这些。

回答by Milen A. Radev

"Current Date/Time":

“当前日期/时间”

CURRENT_TIME and CURRENT_TIMESTAMP deliver values with time zone; LOCALTIME and LOCALTIMESTAMP deliver values without time zone.

CURRENT_TIME 和 CURRENT_TIMESTAMP 提供带时区的值;LOCALTIME 和 LOCALTIMESTAMP 提供没有时区的值。