如何在python中设置protobuf时间戳字段?

2024-09-28 17:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在探索协议缓冲区的使用,并希望使用protobuf3中的新时间戳数据类型。这是我的.proto文件:

syntax = "proto3";

package shoppingbasket;

import "google/protobuf/timestamp.proto";

message TransactionItem {
  optional string product = 1;
  optional int32 quantity = 2;
  optional double price = 3;
  optional double discount = 4;
}

message Basket {
  optional string basket = 1;
  optional google.protobuf.Timestamp tstamp = 2;
  optional string customer = 3;
  optional string store = 4;
  optional string channel = 5;
  repeated TransactionItem transactionItems = 6;
}

message Baskets {
  repeated Basket baskets = 1;
}

从这个.proto文件生成python类之后,我尝试使用生成的类创建一些对象。代码如下:

import shoppingbasket_pb2
from google.protobuf.timestamp_pb2 import Timestamp

baskets = shoppingbasket_pb2.Baskets()
basket1 = baskets.baskets.add()
basket1.basket = "001"
basket1.tstamp = Timestamp().GetCurrentTime()

出现错误时失败:

AttributeError: Assignment not allowed to composite field "tstamp" in protocol message object.

有谁能解释一下为什么这不起作用,因为我很困惑


Tags: 文件importmessagestringgoogleoptionaltimestampproto