Get a timestamp from concatenating day and time columns
我在数据库中有日期和时间字段。 我希望通过连接日期和时间来获得时间戳。 如何在PostgreSQL中执行此操作?
我这样做了:
1 | SELECT EXTRACT(EPOCH FROM TIMESTAMP '2011-05-17 10:40:28'); |
它工作正常。
但是当我尝试替换日期和时间字段时,我收到以下错误:
1 | SELECT EXTRACT(EPOCH FROM TIMESTAMP DAY || ' ' || TIME); |
1
2 ERROR: syntax error at OR near"Day"
LINE 1: ...quest_count > 0 AND (EXTRACT(EPOCH FROM TIMESTAMP DAY || ' ' || TIME)) > (e...
如果
1 | SELECT EXTRACT(EPOCH FROM (DAY + TIME)); |
您只需添加
而且,严格来说,提取时代本身与您的问题无关。
字符串类型
如果您正在讨论字符串文字或
1 | SELECT EXTRACT(EPOCH FROM ('2013-07-18' || ' ' || '21:52:12')::TIMESTAMP); |
要么
1 | SELECT EXTRACT(EPOCH FROM CAST('2013-07-18' ||' '|| '21:52:12' AS TIMESTAMP)); |
你的表格不起作用
1 | <strike>SELECT EXTRACT(EPOCH FROM TIMESTAMP ('2013-07-18' || ' ' || '21:52:12'));</strike> |
这可行:
1 | SELECT EXTRACT(EPOCH FROM"timestamp" ('2013-07-18' || ' ' || '21:52:12')); |
我引用关于类型转换的手册:
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 equivalentfloat8 can. Also, the namesinterval ,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.
大胆强调我的。
它的要点:而是使用前两种语法变体之一。
1 | SELECT EXTRACT(EPOCH FROM (DAY || ' ' || TIME)::TIMESTAMP); |