2017-06-01 172 views
4

我已经从bigquery记录(使用google.cloud.bigquery库)中检索日期时间,并且需要根据“Google地图”中的rfc 3339格式将其发送到Google管理员sdk报告API。 startTime'参数为this api method。该API期待的日期时间,看起来像这样:需要帮助格式化Google API的日期时间时区

2010-10-28T10:26:35.000Z

其中由无tzinfo创建一个Python datetime和调用isoformat像这通常是可能的:

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

我遇到的问题是来自BigQuery的时间戳记包含一个tzinfo对象,并且这会导致isoformat返回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作为startTime。如果我手动从字符串中删除+00:00的API调用工作,但我不知道如何在python中做到这一点,没有一个丑陋的字符串破解。有没有一些干净的方式从日期时间对象中删除它?

我也试了这一点,但结果是一样的:

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

一种可能性是使用带格式字符串的'strftime':'datetime.utcnow()。strftime('%Y-%m-%dT%H:%M:%S.%fZ')' –

回答

2

使用datetime.datetime.strftime()

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

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

+0

谢谢,我认为这正是我需要的。而不是2017-05-31T16:13:26.252000 + 00:00Z我现在有2017-05-31T16:13:26.252000Z,它适用于API。假设'252000'是毫秒,对吗?而Z是没有偏移的UTC,对吧? – Michael

+1

是'%f'为毫秒(查看[可用的strftime指令](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior))。这里的'Z'只是一个字符,意思是Zulu/UTC,它不会对日期时间做任何事情,因此在执行'strftime'之前,您必须首先确保日期时间在Zulu/UTC时区。你所描述的两种情况你应该没问题。仅供参考:如果您必须处理时区,请查看[pytz软件包](https://pypi.python.org/pypi/pytz)。 –

+0

来自bigquery记录的日期时间是UTC,没有偏移,所以应该是好的。再次感谢。 – Michael