'How do i create a protobuf3 Timestamp in python?

I see that there is a Timestamp object but it doesn't seem to work. Using Python 3.6

$ pip install protobuf3

In python:

from google.protobuf.timestamp_pb2 import Timestamp
timestamp = Timestamp()
timestamp.GetCurrentTime()

Nothing is returned. What am I doing wrong?



Solution 1:[1]

ARRGGG I think there was a virtual env problem. It works now!

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
>>> from google.protobuf.timestamp_pb2 import Timestamp
>>> timestamp = Timestamp()
>>> timestamp.GetCurrentTime()
>>> print(timestamp)
seconds: 1521497361
nanos: 600455000

>>>timestamp
seconds: 1521497361
nanos: 600455000

Solution 2:[2]

The only two args of constructing a protobuf Timestamp are seconds and nanos. They are defined as the seconds from the Epoch (1970-01-01 00:00:00). So we can do:

import datetime
from google.protobuf.timestamp_pb2 import Timestamp

t = datetime.datetime.now().timestamp()
seconds = int(t)
nanos = int(t % 1 * 1e9)

proto_timestamp = Timestamp(seconds=seconds, nanos=nanos)

Solution 3:[3]

Simple example:

message Data {
    google.protobuf.Timestamp tstamp = 1;
}

setting value:

message.tstamp.FromDatetime(datetime.datetime.now())

printing received message:

tstamp {
    seconds: 1648070801
    nanos: 661005000
}

Solution 4:[4]

timestamp.GetCurrentTime()

Actually this method fills in the current time rather than getting the current time.

Check documentation here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 P Moran
Solution 2 Kai Zhang
Solution 3 Marcin
Solution 4 Amrut Prabhu