- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在这里看到了类似的问题,例如。 G。 “我想将时间从 13:00 更改为 17:00”,答案始终是“使用 '13:00' + INTERVAL '4 小时'
”
但是,我需要的是将 date_part
值设置为现有日期,而不知道确切的间隔大小,与 date_part
相反(extract
) 函数。
例如:
-- NOT A REAL FUNCTION
SELECT date_set('hour', date, 15)
FROM (VALUES ('2021-10-23 13:14:43'::timestamp), ('2020-11-02 10:00:34')) as dates (date)
结果将是:
2021-10-23 15:14:43
2020-11-02 15:00:34
如您所见,这不能通过简单的 +/- INTERVAL
表达式来完成。
我已经在 SO 上发现的是:
SELECT date_trunc('day', date) + INTERVAL '15 hour'
FROM (VALUES ('2021-10-23 13:14:43'), ('2020-11-02 10:00:34')) as dates (date)
但是这个变体不保留分钟和秒。
不过,我可以解决这个问题,只需添加原始时间戳的分钟、秒和微秒即可:
SELECT date_trunc('day', date) + INTERVAL '15 hour'
+ (extract(minute from date) || ' minutes')::interval
+ (extract(microsecond from date) || ' microseconds')::interval
FROM (VALUES ('2021-10-23 13:14:43.001240'::timestamp), ('2020-11-02 10:00:34.000001')) as dates (date)
这将输出:
2021-10-23 15:14:43.001240
2020-11-02 15:00:34.000001
它解决了问题。
但说实话,我对这个解决方案不太满意。也许有人知道更好的变体?
最佳答案
以下函数背后的想法是清除单位(减去相应的间隔)并添加给定的间隔。
create or replace function timestamp_set(unit text, tstamp timestamp, num int)
returns timestamp language sql immutable as $$
select tstamp+ (num- date_part(unit, tstamp))* format('1 %s', unit)::interval
$$;
检查:
select
date,
timestamp_set('hour', date, 15) as hour_15,
timestamp_set('min', date, 33) as min_33,
timestamp_set('year', date, 2022) as year_2022
from (
values
('2021-10-23 13:14:43'::timestamp),
('2020-11-02 10:00:34')
) as dates (date)
date | hour_15 | min_33 | year_2022
---------------------+---------------------+---------------------+---------------------
2021-10-23 13:14:43 | 2021-10-23 15:14:43 | 2021-10-23 13:33:43 | 2022-10-23 13:14:43
2020-11-02 10:00:34 | 2020-11-02 15:00:34 | 2020-11-02 10:33:34 | 2022-11-02 10:00:34
(2 rows)
尝试一下db<>fiddle.
关于sql - 更改 PostgreSQL 中时间戳的一部分(不是相对),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69684292/
给定一个带有多个 date_time 戳的字符串,我想 提取第一个戳及其前面的文本 候选字符串可以有一个或多个时间戳 后续的 date_time 戳记将被 sep="-" 隔开 后续date_time
是否可以合并从相机拍摄的文本和照片?我想在照片上标记日期和时间,但我在 Google 上找不到任何内容。 最佳答案 使用下面的代码来实现你所需要的。 Bitmap src = Bitm
有没有办法通过 Graph API 戳另一个用户?基于this post ,并使用 Graph Explorer ,我发布到“/USERID/pokes”,我已经授予它(Graph API 应用程序和
我有两个向左浮动的元素。一个是 body 的第一个 child ,另一个是容器的第一个 child ,容器是 body 的第二个 child 。 ...
我是一名优秀的程序员,十分优秀!