我们如何将google.protobuf.Timestamp转换为Ruby DateTime对象?

时间:2017-01-16 18:17:05

标签: ruby time protocol-buffers epoch

此问题没有太多详细信息,我正在进行卡夫卡活动,时间类型为google.protobuf.Timestamp。这些kafka事件正在(通过HTTP)发布到我的rails应用程序,我需要时间以ruby的日期时间格式而不是google.protobuf.Timestamp

3 个答案:

答案 0 :(得分:1)

您可以编写一个双射来将 google.protobuf.Timestamp 转换为 Time,反之亦然:

module ProtobufBijections
  # Converts a Protobuf timestamp to ruby time
  # @param [google.protobuf.Timestamp] protobuf_timestamp
  # @return [Time] Ruby time object
  def to_ruby_time(protobuf_timestamp)
    epoch_micros = protobuf_timestamp.nanos / 1000
    Time.at(protobuf_timestamp.seconds, epoch_micros)
  end

  ...
end

答案 1 :(得分:1)

google-protobuf gem 具有用于众所周知类型的类,例如 google.protobuf.Timestamp 等。

您可以使用 Google::Protobuf::Timestamp.new(data).to_time 以适当的方式从 protobuf 值中获取 Time

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

示例:

> require 'google/protobuf/well_known_types'
> data = {:nanos=>801877000, :seconds=>1618811494}
> Google::Protobuf::Timestamp.new(data)
=> <Google::Protobuf::Timestamp: seconds: 1618811494, nanos: 801877000>
> Google::Protobuf::Timestamp.new(data).to_time
=> 2021-04-19 14:51:34.801877 +0900

答案 2 :(得分:0)

将微秒转换为nanos并使用Time.at(seconds, microseconds_with_frac) → time

epoch_micros = timestamp.nanos / 10 ** 6
Time.at(timestamp.seconds, epoch_micros)

供参考:http://ruby-doc.org/core-2.2.0/Time.html