Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help formatting datetime timezone for Google API

I've retrieved a datetime from a bigquery record (using the google.cloud.bigquery library) and need to send it to the google admin sdk reports API in rfc 3339 format according to the 'startTime' parameter of this api method. The API is expecting the datetime to look like this:

2010-10-28T10:26:35.000Z

Which is normally possible by creating a python datetime without tzinfo and calling isoformat like this:

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

The problem I'm having is that the timestamp coming from BigQuery includes a tzinfo object, and that's causing isoformat to return text that the Google API can't process.

>>> 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'

Specifically, the +00:00 is not accepted by Google's API as startTime. If I manually remove +00:00 from the string the API call works, but I'm not sure how to do this in python without an ugly string hack. Is there some clean way to remove this from the datetime object?

I've also tried this, but results in the same:

>>> timestamp_from_bigquery.replace(tzinfo=None)
'2017-05-31T16:13:26.252000+00:00Z'
like image 437
Michael Avatar asked Jun 01 '17 13:06

Michael


1 Answers

Use datetime.datetime.strftime():

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

Of course make sure the datetimes are in the correct timezone.

like image 74
Paco H. Avatar answered Oct 20 '22 00:10

Paco H.