Python中如何将datetime转换为Protobuf Timestamp?
解决Python中datetime转Protobuf Timestamp适配Google Cloud Optimization V1的问题
核心问题分析
你遇到的两个关键问题:
- 导入的
Timestamp是内部实现类而非官方API,导致属性缺失报错 - 错误调用了
FromDatetime方法的使用方式
正确解决方案
1. 标准导入方式
优先使用官方对外暴露的API导入,IDE提示找不到引用通常是缓存问题,实际代码运行不受影响:
from google.protobuf.timestamp_pb2 import Timestamp
如果IDE报错持续,可尝试:
- 清理IDE缓存(比如PyCharm:
File -> Invalidate Caches...) - 重新安装protobuf依赖:
poetry add protobuf --upgrade
2. 两种正确的datetime转换方式
方式一:实例方法(修改自身)
FromDatetime是实例方法,作用是修改当前Timestamp对象,不返回新实例:
from datetime import datetime from google.protobuf.timestamp_pb2 import Timestamp # 假设timeWindow.startTime是合法的datetime对象(需为UTC时区或带时区信息) timestamp = Timestamp() timestamp.FromDatetime(timeWindow.startTime) startTime = timestamp
方式二:类方法(直接返回实例,推荐)
使用更简洁的类方法from_datetime直接生成转换后的Timestamp对象:
startTime = Timestamp.from_datetime(timeWindow.startTime)
错误原因说明
- 你导入的
google.protobuf.internal.well_known_types.Timestamp是内部私有实现类,不包含对外API的seconds等属性,因此触发AttributeError - 即使导入正确的Timestamp,
Timestamp().FromDatetime(...)的写法也错误:该方法返回None,你试图将其赋值给startTime,后续必然出现数据异常
额外注意
确保转换的datetime对象是UTC时区,或通过datetime.astimezone()明确指定时区,否则转换会抛出时区错误。
内容的提问来源于stack exchange,提问作者Ketterle
相关产品推荐
相关产品推荐

