简体   繁体   中英

How to set a protobuf Timestamp field in python?

I am exploring the use of protocol buffers and would like to use the new Timestamp data type which is in protobuf3. Here is my.proto file:

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;
}

After generating python classes from this.proto file I'm attempting to create some objects using the generated classes. Here's the code:

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()

which fails with error:

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

Can anyone explain to me why this isn't working as I am nonplussed.

See Timestamp .

I think you want:

basket1.tstamp.GetCurrentTime()

You could also parse it:

Timestamp().FromJsonString("2022-03-26T22:23:34Z")

I found this highly confusing, as it differs from how other values was assigned in my demo, so I'd like to add this method using .FromDatetime() :

.proto:

message User {
    int64 id = 1;
    string first_name = 2;
    ...
    string phone_number = 7;
    google.protobuf.Timestamp created_on = 8; # <-- NB
}

The response, UserMsgs.User() , is here a class generated from the above protofile, and is aware of what type each field has.

    def GetUser(self, request, context):
    response = UserMsgs.User()

    if request.id is not None and request.id > 0:
        usr = User.get_by_id(request.id)
        response.id = usr.id
        response.first_name = usr.first_name
        ...
        response.phone_number = str(usr.phone_number)
        response.created_on.FromDatetime(usr.created_on)  # <-- NB
    return response

So instead of assigning response.created_on with = as the others, we can use the built in function .FromDatetime as mentioned here . NB: Notice the lowercase t in Datetime

usr.created_on in my example is a python datetime, and is assigned to a google.protobuf.Timestamp field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM