加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在Rails中以毫秒为单位存储时间

发布时间:2020-12-17 02:10:01 所属栏目:百科 来源:网络整理
导读:我正在尝试在Rails中存储毫秒精度的时间戳,但是当我从数据库中检索记录时,该值会被抬高: record.time_stamp = Time.utc(2017,1,1.35) 保存前检查时间: record.time_stamp.strftime('%H:%M:%S.%L')= "01:01:01.350" record.time_stamp.usec= 350000record.t
我正在尝试在Rails中存储毫秒精度的时间戳,但是当我从数据库中检索记录时,该值会被抬高:

record.time_stamp = Time.utc(2017,1,1.35)

保存前检查时间:

record.time_stamp.strftime('%H:%M:%S.%L')
=> "01:01:01.350" 
record.time_stamp.usec
=> 350000
record.time_stamp.to_f
=> 1483232461.35

保存并重新加载:

record.save!
record.reload

保存后检查时间:

record.time_stamp.strftime('%H:%M:%S.%L')
=> "01:01:01.006"
record.time_stamp.usec
=> 6108
record.time_stamp.to_f
=> 1483232461.0061078
record.read_attribute_before_type_cast("time_stamp") // Read raw value before type casting
=> "2017-01-01 01:01:01.35"

不知道这里发生了什么.存储在DB中的毫秒值是正确的,就像压缩之前的原始值一样(参见最后一行),它只是在重新投入Ruby Time时搞砸了.

笔记:

>我意识到Ruby Time is precise to nanoseconds,while the DB is only precise to microseconds – 但我只是想节省毫秒,所以这不应该是一个因素.
>这不是时区问题.

(规格:Rails / ActiveRecord 4.2.6,ruby 2.3.0,Postgres 9.5.0,OSX)

更新:
我刚尝试在一个新的rails应用程序中使用与我当前应用程序完全相同的rails / ruby?? / postgres版本重现此问题,并且无法做到!而且由于其他人也无法复制,这意味着这是我的应用程序明确特定的东西,我需要进一步挖掘以尝试隔离导致此问题的原因…当我有更多信息时会更新.

解决方法

我无法使用Rails 4.2.6和5.0.5(以及Ruby 2.3.1,Postgres 9.6.4)重现该问题

# Gemfile
ruby '2.3.1'
gem 'rails','4.2.6'
gem 'pg'
require 'active_record'

# example.rb
class Record < ActiveRecord::Base
  establish_connection 
    adapter:  'postgresql',database: 'try_timestamp',username: 'postgres'

  connection.create_table table_name,force: true do |t|
    t.datetime :time_stamp
  end
end

time_stamp = Time.utc 2017,1.35
record     = Record.new time_stamp: time_stamp

p record.time_stamp.strftime('%H:%M:%S.%L')
p record.time_stamp.usec
p record.time_stamp.to_f

record.save!
record.reload

p record.time_stamp.strftime('%H:%M:%S.%L')
p record.time_stamp.usec
p record.time_stamp.to_f


# terminal command
? createdb try_timestamp
? bundle install
? bundle exec ruby example.rb
"01:01:01.350"
350000
1483232461.35
"01:01:01.350"
350000
1483232461.3500001

您可以运行此示例并告诉问题是否在clear rails app上重现?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读