sql - 将时间戳分钟设置为特定值

标签 sql postgresql datetime timestamp

设置时间戳的精确分钟值的最简单方法是什么?

这只会增加分钟数,而不是设置确切的值:

SELECT timestamp_field + interval '2 minutes';

最佳答案

使用date_trunc()在添加 2 分钟之前:

SELECT date_trunc('hour', timestamp_field) + interval '2 minutes';

或者,保留秒和亚秒:

SELECT date_trunc('hour', timestamp_field)
     + interval '2 min'
     + extract('seconds' FROM timestamp_field) * interval '1 sec';

演示:

test=> SELECT now()
test-> UNION ALL
test-> SELECT date_trunc('hour', now())
test->      + interval '2 min'
test->      + extract('seconds' FROM now()) * interval '1 sec';
              now              
-------------------------------
 2021-03-23 03:59:57.373279+01
 2021-03-23 03:02:57.373279+01
(2 rows)

应该比操作文本表示和回传要快得多。

关于sql - 将时间戳分钟设置为特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66756525/

相关文章:

sql - 计算阶段之间的持续时间

datetime - DisplayFormat 属性的 DataFormatString 参数在与 @Html.TextBoxFor() 一起使用时不起作用

r - 如何在 Azure ML 中为 strptime 函数定义当前时区,未知时区 'localtime'

mysql - Access 中的查询非常慢,SQL 服务器可以做得更好吗

java.sql.SQLException : Network error IOException: No route to host?

php - 从多个相关表中检索值

java - 使用 hibernate 从 postgresql 获取 CSV 格式的结果

postgresql - Postgres 9.6 并行 XPath

c# - 将 DateTime 存储到 cookie 中的最佳方法是什么?

c# - C#查询未返回任何内容