gpt4 book ai didi

ruby-on-rails - Ruby:从 Ruby 生成 Google Protobuf 时间戳?

转载 作者:行者123 更新时间:2023-12-02 02:20:07 26 4
gpt4 key购买 nike

这是一个模型博客

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

class Blog < ApplicationRecord

end

我想将模型的 created_at 和 updated_at 转换为 google Protobuf TimeStamp

blog = Blog.first
blog.created_at

如何在形成protobuf消息时将DateTime转换为google Protobuf TimeStamp?

最佳答案

Google protobuf 库有执行此操作的方法:

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

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

关于ruby-on-rails - Ruby:从 Ruby 生成 Google Protobuf 时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66541384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com