postgresql 从串联的日期和时间列获取时间戳

yhuiod9q  于 2022-12-12  发布在  PostgreSQL
关注(0)|答案(3)|浏览(167)

我在数据库中有日期和时间字段。我想通过连接日期和时间来获得时间戳。如何在PostgreSQL中做到这一点?
我已经这样做了:

SELECT EXTRACT(EPOCH FROM TIMESTAMP '2011-05-17 10:40:28');

而且它工作得很好。
但是,当我尝试替换日期和时间字段时,出现以下错误:
第一次

izkcnapc

izkcnapc1#

Identifiers?

It's unclear whether you are using upper-case letters in your identifiers, which requires double-quoting.
Also, Day is a reserved word in SQL and - even though allowed as identifier in Postgres - may require special treatment. I would generally avoid reserved words and basic type names. Double-quoting takes care of it in any case. My standing advice is to use legal, lower-case identifiers that never require double-quoting. See:

  • Are PostgreSQL column names case-sensitive?

date and time types

If your column "Day" is of type date and your column "Time" is of type time , there is a very simple solution:

SELECT EXTRACT(EPOCH FROM ("Day" + "Time"));

You can just add the types date and time to get a timestamp [without time zone] .
Extracting the epoch is unrelated to your question per se. date + time result in a timestamp , that's it.

String types

If you are talking about string literals or columns of type text / varchar , use:

SELECT EXTRACT(EPOCH FROM ('2013-07-18' || ' ' || '21:52:12')::timestamp);

or:

SELECT EXTRACT(EPOCH FROM cast('2013-07-18' ||' '|| '21:52:12' AS timestamp));

Your form does not work:

SELECT EXTRACT(EPOCH FROM TIMESTAMP ('2013-07-18' || ' ' || '21:52:12'));

This would work (note the double-quotes):

SELECT EXTRACT(EPOCH FROM "timestamp" ('2013-07-18' || ' ' || '21:52:12'));

The manual about type casts:
It is also possible to specify a type cast using a function-like syntax:
typename ( expression )
However, this only works for types whose names are also valid as function names. For example, double precision cannot be used this way, but the equivalent float8 can. Also, the names interval , time , and timestamp can only be used in this fashion if they are double-quoted, because of syntactic conflicts. Therefore, the use of the function-like cast syntax leads to inconsistencies and should probably be avoided.
Bold emphasis mine.
Use one of the first two syntax variants.

kognpnkq

kognpnkq2#

SELECT EXTRACT(EPOCH FROM (Day || ' ' || Time)::timestamp);
qrjkbowd

qrjkbowd3#

这对我来说很好:

SELECT CONCAT(Day,' ',Time)::timestamp;

相关问题