AIP-142 时间和时间段
编号 | 142 |
---|---|
原文链接 | https://google.aip.dev/142 |
状态 | 批准 |
创建日期 | 2019-07-16 |
更新日期 | 2019-07-16 |
许多服务需要表示与时间有关的概念。日历和时区是复杂的,同时常见数据交换格式(如JSON)缺乏原生时间概念,因此如何表示时间可能会遇到一些困难。
指南
表示时间的域 应当 使用常用的、普遍使用的组件(如google.protobuf.Timestamp或google.type.Date)来表示时间或时间段类型。这些类型是常用组件,统一使用常用组件,可以让基础设施和工具在交互时,为时间值提供更好的体验。
时间戳
表示绝对时间点(独立于时区或日历)的域 应当 使用google.protobuf.Timestamp类型(该类型在内部使用UNIX时间戳,保持纳秒精度)。
这些域的名字 应当 以 _time
结尾,如 create_time
或 update_time
。重复域名字 应当 以 _times
结尾。
许多时间戳域和某个活动有关(如 create_time
表示可用资源的创建时间)。这些域 应当 以 {imperative}_time
格式命名。例如,如果一本书正在出版,存储事件发生时间的域将使用动词“to publish”的命令形式(“publish”),产生名为 publish_time
的域。域 不应 使用过去时态命名(如 published_time
、 created_time
或 last_updated_time
)。
时间段
用来表示两个时间点之间的跨度(独立于时区或日历)的域 应当 使用google.protobuf.Duration类型。
为了说明时间戳和时间段之间的区别,考虑下面的飞行记录:
// A representation of a (very incomplete) flight log.
message FlightRecord {
// The absolute point in time when the plane took off.
google.protobuf.Timestamp takeoff_time = 1;
// The length (duration) of the flight, from takeoff to landing.
google.protobuf.Duration flight_duration = 2;
}
注意 细心的读者可能会注意到timestamp和duration消息具有同样的结构(
int64 seconds
和int32 nanos
)。它们之间存区别重要差别,它们具有不同的语义。此外,工具可以根据消息类型改变行为。例如基于Python的工具可以将时间戳转换为datetime对象,将时间段转换为timedelta对象。
相对时间段
有时可能需要在流数据中表示时间段。此时 应当 使用google.protobuf.Duration类型,域名字 应当 以 _offset
结尾。为确保含义清晰,域 必须 包含注释,说明偏移量相对于哪个时间点。
为了说明这一点,考虑一个表示音频流片段的资源:
message AudioSegment {
// The duration relative to the start of the stream representing the
// beginning of the segment.
google.protobuf.Duration start_offset = 1;
// The total length of the segment.
google.protobuf.Duration segment_duration = 2;
}
日常用日期和时间
表示日历日期或挂钟时间的域 应当 使用适当的常用组件:
- 日常用日期:google.type.Date
- 挂钟时间:google.type.TimeOfDay
表示日常用日期的域 应当 以 _date
结尾,而表示日常用日期和时间的域 应当 以 _time
结尾。
注意
Date
和TimeOfDay
组件都不包含时区。需要包含时区信息的域 应当 使用DateTime
(见下文)。
日常用时间戳
表示日常用时间戳(日期和时间,可以包含时区)的域 应当 使用google.type.DateTime组件,域名字 应当 以 _time
结尾。
兼容性
有时,由于遗留或兼容性原因,API无法使用常用结构。例如API可能符合某个独立规范,要求时间戳使用整数或ISO-8601字符串。
此时域 可以 使用其他类型,尽量使用以下命名约定:
- 整数域名字包括含义(例如:
time
、duration
、delay
、latency
) 并 将测量单位(有效值:seconds
、millis
、micros
、nanos
)作为末尾后缀。如send_time_millis
。 - 字符串域名字包括含义(例如:
time
、duration
、delay
、latency
),但不包括单位后缀。
在任何情况下,清楚记录预期的格式和使用理由。