gpt4 book ai didi

I want to round off timestamp upto second in snowflake. e.g. 2023-09-03 08:17:48.919 should be converted to 2023-09-03 08:17:49(我想在雪花中将时间戳四舍五入到秒。如2023-09-03 08:17:48.919应转换为2023-09-03 08:17:49)

转载 作者:bug小助手 更新时间:2023-10-25 22:33:26 24 4
gpt4 key购买 nike



I want to round off timestamp up to second in snowflake. e.g. 2023-09-03 08:17:48.919 should be converted to 2023-09-03 08:17:49

我想在雪花中将时间戳四舍五入到秒。如2023-09-03 08:17:48.919应转换为2023-09-03 08:17:49


I tried using TO_CHAR(column_name, 'YYYY-MM-DD HH24:MI:SS') but it is not doing roundoff.

我尝试使用TO_CHAR(COLUMN_NAME,‘YYYY-MM-DD HH24:MI:SS’),但它不执行舍入。


select TO_CHAR(column_name, 'YYYY-MM-DD HH24:MI:SS') from table_name

更多回答

Adding 0.5 seconds before truncating is perhaps good enough?

在截断前添加0.5秒可能就足够了?

What output do you want to see for the following timestamp: 2023-09-03 08:17:48.419.

您希望看到以下时间戳的输出:2023-09-03 08:17:48.419。

优秀答案推荐

SELECT FORMAT(DATEADD(SECOND, CASE WHEN DATEPART(MILLISECOND, '2023-09-03 
08:17:48.919') >= 500 THEN 1 ELSE 0 END, '2023-09-03 08:17:48.919'), 'yyyy-MM-dd
HH:mm:ss') AS rounded_timestamp;


So the classic way to "round anything" is to add half the size of the unit of rounding (thus here 500 milliseconds) and then truncate towards zero. But given time tends to not be negative (yes it can, but I am not solving for that)..

因此,“舍入任何东西”的经典方法是将舍入单位大小的一半(这里是500毫秒)相加,然后向零截断。但是,如果时间不是负的(是的,它可以,但我不会解决这个问题)..


we can use DATEADD and DATE_TRUNC like so:

我们可以这样使用DATEADD和DATE_TRUNC:


select $1 as input
,dateadd('milliseconds', 500, input) as shift_up
,date_trunc('second', shift_up) as rounded_to_sec
from values
('2023-09-03 08:17:48.919'::timestamp),
('2023-09-03 08:17:49.419'::timestamp);

gives the answer we are expecting.

给出了我们期待的答案。


enter image description here


更多回答

Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?

请记住,Stack Overflow不仅仅是为了解决眼前的问题,也是为了帮助未来的读者找到类似问题的解决方案,这需要理解底层代码。这对于我们社区的初学者和不熟悉语法的成员来说尤其重要。考虑到这一点,你能编辑你的答案,包括你正在做的事情的解释以及为什么你认为这是最好的方法吗?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com