go - 使用 google.protobuf.Timestamp 在 Go 中解析具有时区偏移的日期时间戳

标签 go protocol-buffers grpc-go

我正在创建一个将使用 GRPC 和 protobuf 的 Go 应用程序。我的 RPC 服务应接收包含 google.protobuf.Timestamp 类型的消息,对其进行解析并最终将其保存在数据库中或对其执行更多操作。

对于 google.protobuf.Timestamp 类型的有效输入,我感到很困惑。我希望对带有时区偏移量的日期时间戳使用以下格式。

2019-02-15T13:00:00+01:00

这是我正在使用的原型(prototype)文件。

syntax = "proto3"
package example;
import "google/protobuf/timestamp.proto"

service Tester {
 rpc ParseDateTimeStamp(TSRequest) returns (TSReply) {}
}

message TSRequest {
  google.protobuf.Timestamp dts = 1;
}

message TSReply {
 string message = 1;
}

问题是当我向包含日期时间戳的 GRPC 服务器发送消息时。我希望给定的 2019-02-15T13:00:00+01:00 日期时间戳的类型 *tsbp.Timestamp 是有效的,并给我适当的秒数从时代。 (从 timestamp.go 调用 GetSeconds() 之后)

为上面的示例输入调用 ptypes.TimestampString(ts *tspb.Timestamp) 返回 1970-01-01T00:00:00Z

google.protobuf.Timestamp 是否接受带有 +- 偏移量的日期时间戳?

或者我是否必须以 String 类型输入,然后使用 time.Format 解析为 time.Time 而不是使用 protobuf 中的时间戳变量类型?如果是这样,你能提供一个例子吗?

最佳答案

google.protobuf.Timestamp 的 gRPC 消息类型,在内部,只是两个 int64

message Timestamp {
  // Represents seconds of UTC time since Unix epoch
  // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  // 9999-12-31T23:59:59Z inclusive.
  int64 seconds = 1;

  // Non-negative fractions of a second at nanosecond resolution. Negative
  // second values with fractions must still have non-negative nanos values
  // that count forward in time. Must be from 0 to 999,999,999
  // inclusive.
  int32 nanos = 2;
}

所以在这种格式类型中,没有什么要解析的。

一个人通常需要:

  • 字符串格式,如您的 2019-02-15T13:00:00+01:00 并使用 time.Parse< 转换为 time.Time/
  • 然后使用 ptypes.TimestampProto()time.Time 转换为 *tspb.Timestamp

仅供引用,在您引用的输出中,您看到了一个 时间戳(即秒和纳秒均为零)- 因此 "1970-01-01T00:00:00Z"输出。


实现上面的流程:

ts, err := time.Parse(time.RFC3339, "2019-02-15T13:00:00+01:00")

pbts, err := ptypes.TimestampProto(ts) // ptypes.Timestamp:"seconds:1550232000 "

fmt.Println(ptypes.TimestampString(pbts)) // "2019-02-15T12:00:00Z"

Playground

注意:ptype.Timestamp 没有任何时区 - Z 所以是 UTC 时间。因此,如果您需要保留 time.Time 的时区,除了 google.protobuf.Timestamp 消息之外,还需要在 gRPC 消息中发送偏移量。

关于go - 使用 google.protobuf.Timestamp 在 Go 中解析具有时区偏移的日期时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57342875/

相关文章:

python - 标准 TensorFlow 格式的 Unicode

golang grpc transport.newBufWriter 和 bufio.NewReaderSize 不释放内存

go - RPC 错误 : code = Unimplemented desc = RPC method not implemented

protocol-buffers - protobuf 导入 google/protobuf/timestamp.proto

go - 无法导入位于同一目录中的包

GO lang异常处理

语言 : lack of contains method design-justification

docker - 多阶段构建图像不起作用,而正常构建可以

protocol-buffers - Protocol Buffer 3 : graphical (GUI) tool for seriliazation and deserialization

c++ - Protobuf对象在传递给动态库时损坏