【问题标题】:calculate time difference in rails postgresql query计算rails postgresql查询中的时间差
【发布时间】:2019-04-24 02:02:51
【问题描述】:

我需要在 Rails(具有 Postgres 数据库)中获取时差作为查询结果

Brute Force Approach

我从我的数据库中查询了所有项目,然后迭代每条记录,然后以小时为单位计算时间差,这非常慢。

1) @image_retouch_items = ImageRetouchItem.where(:status => '0') = Retrieved all data
2) @image_retouch_items.each do |retouch_item|
      latency_date = ((Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round
   end

Optimized

我需要计算查询本身的时间(小时)差异,如何实现

like - ImageRetouchItem.where(:status => '0').select('(Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round')

【问题讨论】:

    标签: ruby-on-rails postgresql ruby-on-rails-3 activerecord


    【解决方案1】:

    Postgres 可以使用其内部的current_timestamp 轻松为您做到这一点:

    ImageRetouchItem.where(:status => '0')
                    .select("*, round(extract(epoch from(current_timestamp - created_at)) / 3600)::int as latency_date")
    

    current_timestamp - created_at 将返回一个间隔。通过从该间隔中提取epoch,我们将其转换为秒数,然后我们使用 Postgres round() 函数将其除以 3600 得到小时和四舍五入。我继续使用::int 将结果转换为整数,但这是可选的。

    image_retouch_item 对象现在将有一个 latency_date 属性,该属性将包含以小时为单位的延迟,四舍五入到最接近的小时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      相关资源
      最近更新 更多