在 Postgres 中获取一天中的秒数

Tim*_*nce 6 postgresql datetime

在 Java 中,我们使用 Joda-Time 来获取一天中的秒数作为 int 值(尽管是日期):

date: 10-10-2014 00:00:30 -> second 30 of day
date: 11-10-2014 00:01:30 -> second 90 of day
date: 12-10-2014 00:02:00 -> second 120 of day
Run Code Online (Sandbox Code Playgroud)

有没有办法在 PostgresSQL 中做同样的事情?

Erw*_*ter 8

extract()epoch从铸造到之后的时间成分time(有效地除去的时间成分):

SELECT extract(epoch FROM ts::time) AS seconds_of_day
Run Code Online (Sandbox Code Playgroud)

您将获得“秒数”,包括小数秒(如果有)。
非常简短和快速。

测试(使用明确的ISO 格式的时间戳):

SELECT extract(epoch FROM ts::time) AS seconds_of_day
FROM  (
   VALUES 
     ('2014-10-12 00:00:30'::timestamp)   --    30
   , ('2014-10-12 00:01:30')              --    90
   , ('2014-10-12 00:02:00')              --   120
   , ('2014-10-12 12:00:00')              -- 43200
   , ('1999-12-23 23:59:59')              -- 86399
   , ('1999-12-23 23:59:59.123456')       -- 86399.123456
  ) t(ts);
Run Code Online (Sandbox Code Playgroud)

db<>在这里摆弄


a_h*_*ame 6

使用extract()方法:

select extract(second from current_timestamp) +
       extract(minute from current_timestamp) * 60 +
       extract(hour from current_timestamp) * 60 * 60;
Run Code Online (Sandbox Code Playgroud)

当然,这可以放入一个函数中:

create or replace function total_seconds(p_timestamp timestamp)
 returns int
as
$$
  select (extract(second from p_timestamp) +
         extract(minute from p_timestamp) * 60 +
         extract(hour from p_timestamp) * 60 * 60)::int;
$$
language sql;
Run Code Online (Sandbox Code Playgroud)

更多细节在手册中:http :
//www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT