【发布时间】:2017-05-31 15:52:13
【问题描述】:
这个问题没有太多细节,我收到了一个 kafka 事件,其中时间类型为google.protobuf.Timestamp。这些 kafka 事件正在(通过 HTTP)发布到我的 rails 应用程序,我需要时间以 ruby 的日期时间格式而不是 google.protobuf.Timestamp
【问题讨论】:
标签: ruby time protocol-buffers epoch
这个问题没有太多细节,我收到了一个 kafka 事件,其中时间类型为google.protobuf.Timestamp。这些 kafka 事件正在(通过 HTTP)发布到我的 rails 应用程序,我需要时间以 ruby 的日期时间格式而不是 google.protobuf.Timestamp
【问题讨论】:
标签: ruby time protocol-buffers epoch
将微秒转换为纳秒并使用Time.at(seconds, microseconds_with_frac) → time
epoch_micros = timestamp.nanos / 10 ** 6
Time.at(timestamp.seconds, epoch_micros)
【讨论】:
/ 10**6?是错字吗?应该是/10 ** 3。
您可以编写一个双射将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。
示例:
> 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
【讨论】: