我试图在 Rails 中存储一个毫秒级精度的时间戳,但是当我从数据库中检索记录时该值被抬高了:
record.time_stamp = Time.utc(2017,1,1,1,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"
不确定这里发生了什么。存储在数据库中的毫秒值是正确的,类型转换前的原始值也是正确的(见最后一行),只是在转换回 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,1,1,1,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 应用程序上重现?
关于ruby-on-rails - 在 Rails 中以毫秒为单位存储时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46800828/