postgresql 如何在 Postgres 中格式化“带时区的时间”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1942994/
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-19 23:56:40  来源:igfitidea点击:

How to format "time with time zone" in Postgres?

sqldatabasepostgresqltimeformatting

提问by griffin

I have a database field of type time with time zone. How can I query this field in EST5EDT time zone with the output format hh:mm:ss?

我有一个类型的数据库字段time with time zone。如何使用输出格式 hh:mm:ss 在 EST5EDT 时区中查询此字段?

All I can find is using multiple calls to EXTRACT:

我能找到的只是使用多次调用EXTRACT

SELECT EXTRACT(HOUR FROM TIME WITH TIME ZONE '20:38:40-07' AT TIME ZONE 'EST5EDT');

[Edit:]

[编辑:]

To be clear, this query:

需要明确的是,这个查询:

SELECT TIME WITH TIME ZONE '20:38:40.001-07' AT TIME ZONE 'EST5EDT';

Returns "22:38:40.001" but I just want "22:38:40" as the output.

返回“22:38:40.001”但我只想要“22:38:40”作为输出。

回答by OMG Ponies

Use the TO_CHAR()function:

使用TO_CHAR()函数:

SELECT TO_CHAR(date '2001-09-28' +time, 'HH24:MI:SS')

Seeing that TO_CHAR only accepts the timestamp datatype, you need to concatentate an arbitrary date value to your time value.

看到 TO_CHAR 只接受时间戳数据类型,您需要将任意日期值连接到您的时间值。

回答by Magnus Hagander

"time with time zone" is basically a bogus datatype, and as such isn't really supported in a lot of cases.

“带时区的时间”基本上是一种虚假的数据类型,因此在很多情况下并不真正受支持。

How do you define "time with time zone"? Time zones are dependent on dates, which aren't included in the datatype, and thus it's not fully defined. (yes, it's mandatory by the SQL standard, but that doesn't make it sane)

您如何定义“带时区的时间”?时区取决于日期,日期不包含在数据类型中,因此它没有完全定义。(是的,这是 SQL 标准的强制性要求,但这并不能说明问题)

You're probably best off first fixing what datatype you're using. Either use timestamp with time zone, or use time (without time zone).

您可能最好先修复您正在使用的数据类型。要么使用带时区的时间戳,要么使用时间(不带时区)。

回答by Roland Bouman

You can simply use CAST and CAST to the time type:

您可以简单地将 CAST 和 CAST 用于时间类型:

SELECT CAST(now() AS TIME)

(Of course, the result will have a different data type)

(当然,结果会有不同的数据类型)