Saving Time with Milliseconds in Rails

I am trying to save a timestamp with millisecond precision in Rails, but the value gets up when I retrieve the record from the DB:

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

Check the time before saving:

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

Save and reload:

record.save!
record.reload

Check time after saving:

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"

Not sure what is going on here. The millisecond value stored in the database is correct, just like the original value before the type (see the last line), it just gets screwed when returning to Ruby Time.

NOTES:

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


UPDATE:
rails rails/ruby ​​/postgres, , ! , , - , , , ... , .

+4
3

vincenty. emptor...

+1

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?

+1

Check the database / table timezone against the Rails timezone and the system timezone, it looks like you have a 5 hour difference between what you save and what it returns, which matches the difference between UTC and EST.

-1
source

Source: https://habr.com/ru/post/1687682/


All Articles