在Postgres中将时间以mm:ss格式转换为秒

时间:2018-08-16 11:00:59

标签: sql datetime psql

使用Postgres 9.3.5

我的表的text字段中的持续时间数据存储为分钟:秒,

i.e 4:52

我希望该值是总秒数(即4 x 60)+ 52 = 292

但是表中还包含诸如

的值
3:34:21 (3 hours, 34  minutes and 21 seconds)
21 (21 seconds)

在所有这些情况下,如何编写SQL来纠正以秒为单位的计算持续时间。

更新

select (case when duration like '%:%:%'
             then extract(epoch from duration::time)
             else extract(epoch from ('00:' || duration) ::time)
 end
)as seconds
from discogs.track t1
;

所以我有这个,但是不幸的是,某些值不是很有效,导致失败

00:70:01

如何忽略这些值或将其转换(即70 x 60 + 1)

2 个答案:

答案 0 :(得分:1)

http://sqlfiddle.com/#!17/9eecb/19379

我将%:%文本扩展为%:%:%文本,然后仅在定界符';'上进行拆分。所以我得到了可以在计算中使用的整数值。

SELECT 
    orig_duration,
    hours_in_seconds + minutes_in_seconds + seconds as seconds 
FROM (
    SELECT  
        orig_duration,
        (split_part(duration, ':', 1))::int * 60 * 60 as hours_in_seconds,
        (split_part(duration, ':', 2))::int * 60 as minutes_in_seconds,
        (split_part(duration, ':', 3))::int as seconds
    FROM (
        SELECT
            duration as orig_duration,
            case when duration like '%:%:%' then duration else '00:' || duration end as duration
        FROM (
            SELECT unnest(ARRAY['70:01','3:34:21','4:52']::text[]) as duration
        )s
    )s
)s

结果:

orig_duration  seconds  
-------------  -------  
70:01          4201     
3:34:21        12861    
4:52           292   

答案 1 :(得分:0)

您可以将值转换为时间并提取时间分量。您确实需要考虑变量格式:

select (case when t like '%:%:%'
             then extract(epoch from t::time)
             else extract(epoch from ('00:' || t) ::time)
        end) as seconds

您添加了新格式。您可以这样做:

select (case when t like '%:%:%'
             then extract(epoch from t::time)
             when t like '%:%'
             then extract(epoch from ('00:' || t) ::time)
             else t::int
        end) as seconds