如何在Google ProtoBuf中表示空时间戳?
我正在读取来自postgreSQL数据库的DateTime(其中一些是空的)到protobuf TimeStamps中。
message test {
google.protobuf.TimestampValue TransactionTime =1;
}
不幸的是,没有像google.protobuf.TimestampValue这样的动物。
任何帮助都是非常感谢的。
提亚
发布于 2022-05-18 14:51:09
正如@JayantSeth所指出的,您应该使用google.protobuf.Timestamp
。
由于Protobuf
禁止将字段设置为null
,所以可以使用默认值在应用程序中表示null
。message Timestamp
中有两个字段
message Timestamp {
// Represents seconds of UTC time since Unix epoch
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
// 9999-12-31T23:59:59Z inclusive.
int64 seconds = 1;
// Non-negative fractions of a second at nanosecond resolution. Negative
// second values with fractions must still have non-negative nanos values
// that count forward in time. Must be from 0 to 999,999,999
// inclusive.
int32 nanos = 2;
}
int64
和int32
类型的默认值都是0
。因此,如果从Postgres读取的值为null,则可以将其设置为0。
Timestamp timestamp;
timestamp.set_seconds(0);
timestamp.set_nanos(0);
在您的应用程序中,您可以将timestamp(0)
视为null
。
发布于 2022-11-16 23:32:29
我同意拉姆齐的回答。在Python中,检查null的一个好方法是检查这样的秒或纳秒字段:
from google.protobuf import timestamp_pb2
timestamp = timestamp_pb2.Timestamp()
if timestamp.seconds:
# A valid non-null date was passed
else:
# The date field was left empty; act accordingly.
https://stackoverflow.com/questions/72209861
复制相似问题