将时间和日期转换为时间戳

时间:2020-10-28 16:16:29

标签: sql string postgresql datetime

我有以下日期:

Wed Sep 16 2020 14:23:49 GMT+0000 (Coordinated Universal Time)

如何将其转换为时间戳?

情况:

'Wed Sep 16 2020 14:23:49 GMT+0000 (Coordinated Universal Time)'::timestamp

无效。

3 个答案:

答案 0 :(得分:1)

假设您正在使用给定的整个字符串:


select  to_timestamp('Wed Sep 16 2020 14:23:49 GMT+0000 (Coordinated Universal Time)', 'Dy Mon DD YYYY HH24:MI:SS GMT TZH')::timestamp;

to_timestamp     
---------------------
 2020-09-16 07:23:49


我在PDT中,所以时间到了。

有关to_timestamp以及格式字符串的元素含义的更多信息,请参见此处:

https://www.postgresql.org/docs/current/functions-formatting.html

答案 1 :(得分:0)

cast()

select cast('Wed Sep 16 2020 14:23:49 GMT+0000' as timestamp)
select 'Wed Sep 16 2020 14:23:49 GMT+0000'::timestamp

或者,如果您希望生成timestamp with time zone

select cast('Wed Sep 16 2020 14:23:49 GMT+0000' as timestamp with time zone)
select 'Wed Sep 16 2020 14:23:49 GMT+0000'::timestamp with time zone

Demo on DB Fiddle

答案 2 :(得分:0)

一个简单的转换有效:

select 'Wed Sep 16 2020 14:23:49 GMT+0000'::timestamp 

或者如果您需要时区:

select 'Wed Sep 16 2020 14:23:49 GMT+0000'::timestamptz

您可以只取初始部分:

select left('Wed Sep 16 2020 14:23:49 GMT+0000', 33)::timestamp