How to set a protobuf Timestamp field in python?

Question:

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.

Asked By: jamiet

||

Answers:

See Timestamp.

I think you want:

basket1.tstamp.GetCurrentTime()
Answered By: DazWilkin

You could also parse it:

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

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.

Answered By: Eiriks
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.