简体   繁体   English

将 varchar 时间与 Redshift 中的时间戳相加

[英]Sum varchar time to a timestamp in Redshift

I am trying to sum a timestamp with a time that I have to cast from varchar to time.我正在尝试将时间戳与我必须从 varchar 转换为 time 的时间相加。 This is my attempt:这是我的尝试:

select 
    my_timestamp + cast(my_str_time as time) as my_end_time
from my_db.my_table;

my_timestamp format (already a timestamp ): my_timestamp格式(已经是timestamp ):

2022-07-16 02:51:11
2022-07-16 03:18:06
...

my_str_time format (which is a varchar of 50 in the HH:mm:ss format): my_str_time格式(在HH:mm:ss格式中是 50 的 varchar):

00:03:51 
00:04:13
...

The error I'm getting:我得到的错误:

specified types or functions (one per info message) not supported on redshift tables

Is there any way to calculate this or I would have to alter that varchar column to time?有没有办法计算这个,或者我必须改变那个 varchar 列到时间?

You can try to use a combination of to_timestamp and extract (not too pretty but it should work):您可以尝试使用 to_timestamp 和 extract 的组合(不太漂亮,但应该可以):

extract (sec from to_timestamp (my_str_time,'hh:mi:ss')),提取(秒从to_timestamp (my_str_time,'hh:mi:ss')),

This is what worked for me (very inefficient):这对我有用(非常低效):

with my_times as (
    select
        my_timestamp as my_start_time,
        my_time,
        SUBSTRING(my_time, 0, 3)::integer as my_time_hour,
        SUBSTRING(my_time, 4, 2)::integer as my_time_min,
        SUBSTRING(my_time, 7, 2)::integer as my_time_sec
    from my_db.my_table
)
select
    my_start_time,
    my_time,
    dateadd(HOUR, my_time_hour, dateadd(MINUTE, my_time_min, dateadd(SECOND, my_time_sec, my_start_time))) as my_end_time
from my_times;

Or even better as Bill suggested:或者像比尔建议的那样更好:

select
    my_timestamp,
    my_time,
    my_timestamp + cast(my_time as interval) as my_end_time
from my_db.my_table
limit 5;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM