You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang中如何将time.Time类型转换为Protobuf Timestamp格式?

Go time.Time 转 Protobuf Timestamp 实现方法

你的实现思路没有问题,这是Protobuf和Go标准库时间类型互转的常规场景,对应转换方法如下:

  • 如果你使用新版官方Protobuf依赖(google.golang.org/protobuf,当前官方推荐版本):
    直接调用timestamppb.New()方法即可完成转换,示例代码:
    import "google.golang.org/protobuf/types/known/timestamppb"
    
    // 假设你的time.Time类型变量名为 srcTime
    pbTimestamp := timestamppb.New(srcTime)
    
  • 如果你使用旧版Protobuf依赖(github.com/golang/protobuf):
    调用ptypes.TimestampProto()方法转换,需要额外处理返回的错误:
    import "github.com/golang/protobuf/ptypes"
    
    pbTimestamp, err := ptypes.TimestampProto(srcTime)
    if err != nil {
      // 仅当输入的time.Time值超出Protobuf Timestamp表示范围时会报错,按需处理错误
    }
    

注意:你当前的时间值10-30 00:49:07.1236缺少年份、时区信息,需要先确保构造time.Time变量时已补全对应正确参数,否则转换后的Protobuf Timestamp值会不符合预期。

内容的提问来源于stack exchange,提问作者FestiveHydra235

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:36:07