【问题标题】:How can we convert google.protobuf.Timestamp to Ruby DateTime object?我们如何将 google.protobuf.Timestamp 转换为 Ruby DateTime 对象?
【发布时间】:2017-05-31 15:52:13
【问题描述】:

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

【问题讨论】:

    标签: ruby time protocol-buffers epoch


    【解决方案1】:

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

    【讨论】:

    • 你为什么/ 10**6?是错字吗?应该是/10 ** 3
    【解决方案2】:

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

    【讨论】:

    • 对于不知道“双射”意味着什么的其他人:“......两个集合的元素之间的函数,其中一个集合的每个元素都与另一个元素的一个元素配对设置”
    【解决方案3】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 2011-03-14
      相关资源
      最近更新 更多