需要帮助格式化 Google API 的日期时间时区

Need help formatting datetime timezone for Google API

我从 bigquery 记录中检索了一个日期时间(使用 google.cloud.bigquery 库)并需要将其发送到 google admin sdk 报告 API in rfc 3339 format according to the 'startTime' parameter of this api method. API 期望日期时间如下所示:

2010-10-28T10:26:35.000Z

这通常可以通过创建一个没有 tzinfo 的 python 日期时间并像这样调用 isoformat 来实现:

>>> now = datetime.utcnow()
>>> now = now.isoformat("T") + "Z"
>>> now
'2017-06-01T13:05:32.586760Z'

我遇到的问题是来自 BigQuery 的时间戳包含一个 tzinfo 对象,这导致 return 文本的等格式 Google API 无法处理.

>>> timestamp_from_bigquery
'datetime.datetime(2017, 5, 31, 16, 13, 26, 252000, tzinfo=<UTC>)'
>>> timestamp_from_bigquery.isoformat("T") + "Z"
'2017-05-31T16:13:26.252000+00:00Z'

具体来说,Google 的 API 不接受 +00:00 作为开始时间。如果我从字符串中手动删除 +00:00,API 调用会起作用,但我不确定如何在 python 中执行此操作而不会出现丑陋的字符串 hack。有没有一些干净的方法可以从日期时间对象中删除它?

我也试过这个,但结果是一样的:

>>> timestamp_from_bigquery.replace(tzinfo=None)
'2017-05-31T16:13:26.252000+00:00Z'

使用datetime.datetime.strftime():

datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
timestamp_from_bigquery.strftime('%Y-%m-%dT%H:%M:%S.%fZ')

当然要确保日期时间在正确的时区。