You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将datetime转换为Protobuf Timestamp?

解决Python中datetime转Protobuf Timestamp适配Google Cloud Optimization V1的问题

核心问题分析

你遇到的两个关键问题:

  1. 导入的Timestamp是内部实现类而非官方API,导致属性缺失报错
  2. 错误调用了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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 06:45:13