Convert datetime to protobuf Timestamp in Python

Viewed 8739

So I'm trying to prepare a message with Python that takes a Timestamp, but I'm having trouble converting a datetime to a protobuf Timestamp.

Here's what I've tried so far:

from google.protobuf.timestamp_pb2 import Timestamp
import datetime
now = datetime.datetime.now()
timestamp = Timestamp()
timestamp.FromDatetime(now)

However, I'm getting an error AttributeError: 'Timestamp' object attribute 'seconds' is read-only

How can I create a Timestamp from a datetime?

1 Answers

This code is working fine on my machine

from google.protobuf.timestamp_pb2 import Timestamp
import datetime
now = datetime.datetime.now()
timestamp = Timestamp()
timestamp.FromDatetime(now)

Output:

seconds: 1591859232
nanos: 803377000
Related