如何在 PostgreSQL 中为日期添加可变的小时数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15160207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a variable number of hours to a date in PostgreSQL?
提问by Daniel Magliola
Apparently, PostgreSQL doesn't have DATEADD
, because you can just use the +
or -
operators.
显然,PostgreSQL 没有DATEADD
,因为您可以只使用+
or-
运算符。
I need to add a number of hours to a date, which is accomplished like this:
我需要为一个日期添加几个小时,这是这样完成的:
date_field + interval '8.25 hour'
Which is great, but I need the number of hours to come from a field in the table. Would be something like this:
这很好,但我需要来自表中字段的小时数。会是这样的:
date_field + interval start_time 'hour'
I can't find anywhere how to do this. Is this actually impossible?
我在任何地方都找不到如何做到这一点。这真的不可能吗?
I don't mind resorting to ugly hacks like taking the field value and dividing by 3600, multiplying by 86400. Whatever I need to do, but I haven't found any way to do that either.
我不介意诉诸丑陋的技巧,例如取字段值并除以 3600,再乘以 86400。无论我需要做什么,但我也没有找到任何方法来做到这一点。
回答by Erwin Brandstetter
Since you want to add hours, it should rather be:
由于您想添加hours,它应该是:
SELECT date_field + interval '1h' * start_time
start_time
can be any numerical value.
start_time
可以是任何数值。
回答by Daniel Magliola
Found the answer, in another SO question:
在另一个 SO 问题中找到了答案:
date + interval '1' minute * FLOOR(start_time * 60)
Hope that helps anyone
希望能帮助任何人
回答by Willie Z
The one worked for me is
对我有用的是
SELECT date_field + interval '1' HOUR * start_time
start_timecan be any numerical value.
start_time可以是任何数值。
回答by Rohil Patel
If anyone wants to add in time stamp then
如果有人想添加时间戳,那么
select time '05:00' - interval '2 hours'