如何使用 postgres 将时间间隔转换为小时数?
间隔
4 days 10:00:00
假设我有一个像postgres 中的 。 我如何将其转换为小时数(在本例中为 106?)是否有函数或者我应该硬着头皮做类似的事情
extract(days, my_interval) * 24 + extract(hours, my_interval)
Say I have an interval like
4 days 10:00:00
in postgres. How do I convert that to a number of hours (106 in this case?) Is there a function or should I bite the bullet and do something like
extract(days, my_interval) * 24 + extract(hours, my_interval)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
可能最简单的方法是:
Probably the easiest way is:
如果你想要整数,即天数:
If you want integer i.e. number of days:
要获取天数,最简单的方法是:
据我所知,它会返回与以下内容相同的结果:
To get the number of days the easiest way would be:
As far as I know it would return the same as:
::int
转换遵循舍入原则。如果您想要不同的结果(例如向下舍入),可以使用相应的数学函数,例如
floor
。The
::int
conversion follows the principle of rounding.If you want a different result such as rounding down, you can use the corresponding math function such as
floor
.如果转换表字段:
定义字段,使其包含秒:
提取值。 记住要转换为 int 否则,一旦间隔很大,你可能会得到一个不愉快的惊喜:
EXTRACT(EPOCH FROM field)::int
If you convert table field:
Define the field so it contains seconds:
Extract the value. Remember to cast to int other wise you can get an unpleasant surprise once the intervals are big:
EXTRACT(EPOCH FROM field)::int
如果您想在添加间隔后仅以日期类型显示结果,则应尝试此
Select (current_date +interval 'x day')::date;
If you want to display your result only in date type after adding the interval then, should try this
Select (current_date + interval 'x day')::date;
避免到处出现冗长的
提取纪元
的函数。 返回秒数,因此小时需要int_interval('1 day') / 3600
A function to avoid having verbose
extract epoch
all over the place. Returns seconds so for hours needsint_interval('1 day') / 3600
Usage
我正在使用 PostgreSQL 11,我创建了一个函数来获取 2 个不同时间戳之间的小时数
I'm working with PostgreSQL 11, and I created a function to get the hours betweeen 2 differents timestamps
这是计算总天数的简单查询。
Here is the simple query which calculates total no of days.