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

How can we convert google.protobuf.Timestamp to Ruby DateTime object?

这个问题没有太多细节,我收到一个时间类型为 google.protobuf.Timestamp 的 kafka 事件。这些 kafka 事件正在(通过 HTTP)发布到我的 rails 应用程序,我需要时间采用 ruby 的日期时间格式而不是 google.protobuf.Timestamp

将微秒转换为纳秒并使用 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

您可以编写双射将 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

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