[英]Redshift: Conversion of string field in HH:MM:SS format to seconds and backwards
我一直在尋找一種簡單的方法將字符串字段從HH:MM:SS
格式轉換為 Redshift 中的秒數,因為TIME_TO_SEC
function 不存在。
我有一個呼叫中心數據庫,其中包含一個格式為HH:MM:SS
的字符串字段。 例如,如果它是00:05:10
那么我需要將它轉換為310
。 我自己想出了以下方法,但必須有更好的方法:
(SPLIT_PART("HANDLE TIME", ':', 1) * 3600) + (SPLIT_PART(SPLIT_PART("HANDLE TIME", ':', 2),':', 1) * 60) + CAST(SPLIT_PART("HANDLE TIME", ':', 3) AS INT)
一旦我總結了秒數,我需要將秒數轉換回HH:MM:SS
格式。 所以1249
將成為字符串00:20:49
。 在 MYSQL 中如此簡單,在 RedShift 中則不然。
任何幫助將不勝感激。
不幸的是,我手頭沒有 Redshift,但您可以執行以下操作:
select datediff(second,
timestamp('2000-01-01'),
timestamp('2000-01-01 ' || handle_time)
)
Redshift 沒有專門用於此的功能。 但是,它有一個很棒的功能,稱為UDF ,它支持 python,因此它將是完美的選擇。
1.要將秒數轉換為 hh:mm:ss(或天數,hh:mm:ss),請在 redshift 中創建此 UDF -
CREATE FUNCTION to_hhmmss (a bigint)
RETURNS character varying
STABLE
AS $$
import datetime
return str(datetime.timedelta(seconds=a))
$$ LANGUAGE plpythonu;
它接受一個“大整數”(秒)值作為參數並返回一個字符串(hh:mm:ss 格式的時間)
示例輸出 -
db=# select to_hhmmss_1(12004);
to_hhmmss_1
-------------
3:20:04
(1 row)
db=# select to_hhmmss_1(120040);
to_hhmmss_1
----------------
1 day, 9:20:40
(1 row)
2.將 hh:mm:ss 轉換為秒 -
CREATE FUNCTION to_seconds (time_str varchar(20))
RETURNS integer
STABLE
AS $$
h, m, s = time_str.split(':')
return int(h) * 3600 + int(m) * 60 + int(s)
$$ LANGUAGE plpythonu;
此函數將接受一個字符串(時間單位為 hh:mm:ss)並返回一個整數(秒)。 示例輸出 -
db=# select to_seconds('1:00:00');
to_seconds
------------
3600
(1 row)
您可以使用 cast 和 trim(但您也可以使用 extract)
使用鑄造和修剪:
select
'10:20:23' as time_col,
cast(trim(split_part(time_col, ':', 1)) as int) * 3600 + cast(trim(split_part(time_col, ':', 2)) as int) * 60 + cast(trim(split_part(time_col, ':', 3)) as int) as total_seconds
time_col | total_seconds
10:20:23 | 37223
如果你有 mm:ss 而不是你可以把所有東西都“移”下來
select
'20:23' as time_col,
cast(trim(split_part(time_col, ':', 1)) as int) * 60 + cast(trim(split_part(time_col, ':', 2)) as int) as total_seconds
time_col | total_seconds
20:23 | 1223
使用提取物:
select
'10:20:23' as time_col,
extract(hour from time_col::time) as hour,
extract(minute from time_col::time) as minute,
extract(second from time_col::time) as second,
hour * 3600 + minute * 60 + second as total_seconds
time_col|hour|minute|second|total_seconds
10:20:23|10 |20 |23 |37223
Extract 不適用於 MM:SS,因為您必須按時間投射。
回到時間戳/時間格式:
to_char(date_trunc('second', interval '1 second' * total_seconds), 'HH24:MI:SS') as time_format
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.