在 PostgreSQL 中将 <integer> 秒添加到 <timestamp>

问题描述 投票:0回答:2

我有一个包含以下列的项目表:

  • start_time
    栏目(
    timestamp without time zone
    )
  • expiration_time_seconds
    栏目(
    integer
    )

例如,一些值为:

SELECT start_time, expiration_time_seconds 
   FROM whatever 
       ORDER BY start_time;

         start_time         | expiration_time_seconds
----------------------------+-------------------------
 2014-08-05 08:23:32.428452 |                  172800
 2014-08-10 09:49:51.082456 |                    3600
 2014-08-13 13:03:56.980073 |                    3600
 2014-08-21 06:31:38.596451 |                    3600
 ...

如何将过期时间(以秒为单位)添加到 start_time 中?

我尝试为

interval
命令格式化时间间隔字符串,但失败了:

blah=> SELECT interval concat(to_char(3600, '9999'), ' seconds');
ERROR:  syntax error at or near "("
LINE 1: SELECT interval concat(to_char(3600, '9999'), ' seconds');
time casting timedelta
2个回答
106
投票

技巧是创建一个固定的间隔并将其乘以列中的秒数:

SELECT start_time, 
       expiration_time_seconds, 
       start_time + expiration_time_seconds * interval '1 second'
FROM whatever 
ORDER BY start_time;

        start_time          | expiration_time_seconds |          end_time
----------------------------|-------------------------|----------------------------
 2014-08-05 08:23:32.428452 |                  172800 | 2014-08-07 08:23:32.428452
 2014-08-10 09:49:51.082456 |                    3600 | 2014-08-10 10:49:51.082456
 2014-08-13 13:03:56.980073 |                    3600 | 2014-08-13 14:03:56.980073
 2014-08-21 06:31:38.596451 |                    3600 | 2014-08-21 07:31:38.596451

0
投票

从版本 9.5 开始,可以使用

make_interval
函数创建间隔,如下所示:

make_interval(secs => 10)

还可以使用

+
操作数轻松将间隔添加到时间戳中:

start_time + make_interval(secs => 10)

它将向

start_time
添加 10 秒并返回新的时间戳

© www.soinside.com 2019 - 2024. All rights reserved.