Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Generate Google Protobuf TimeStamp from Ruby?

Here is a model blog.

# id  :bigint(8)
#  created_at                  :datetime         not null
#  updated_at                  :datetime         not null

class Blog < ApplicationRecord

end

I would like to convert model's created_at and updated_at to google Protobuf TimeStamp

blog = Blog.first
blog.created_at

How to convert DateTime to google Protobuf TimeStamp when forming a protobuf message?

like image 917
Ryan Lyu Avatar asked Jul 19 '26 17:07

Ryan Lyu


2 Answers

Google protobuf library has methods to do it:

require 'google/protobuf/well_known_types'

# Convert ruby Time to protobuf value
time = Time.current
Google::Protobuf::Timestamp.new.from_time(time)

# Convert protobuf value to ruby Time
data = {:nanos=>801877000, :seconds=>1618811494}
Google::Protobuf::Timestamp.new(data).to_time

See: https://github.com/protocolbuffers/protobuf/blob/f763a2a86084371fd0da95f3eeb879c2ff26b06d/ruby/lib/google/protobuf/well_known_types.rb#L74-L97

like image 116
zato Avatar answered Jul 22 '26 09:07

zato


If you are using Ruby On Rails, you can do it in the following way:

## Convert Ruby DateTime to Google::Protobuf::Timestamp
time = DateTime.now
seconds = time.to_i
nanos = time.nsec
gpt = Google::Protobuf::Timestamp.new(seconds: seconds, nanos: nanos)


## Convert Google::Protobuf::Timestamp to ruby DateTime
micros = gpt.nanos / 10 ** 3
time2 = Time.at(gpt.seconds, micros)

Reference

  1. ActiveSupport: DateTime#nsec
  2. Stack Overflow: How can we convert google.protobuf.Timestamp to Ruby DateTime object?
like image 24
Ryan Lyu Avatar answered Jul 22 '26 07:07

Ryan Lyu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!