7

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'
Michael
  • 1,428
  • 3
  • 15
  • 34
  • 2
    One possibility would be to use `strftime` with a format string: `datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')` – Paco H. Jun 01 '17 at 13:22

1 Answers1

8

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.

Paco H.
  • 2,034
  • 7
  • 18
  • Thanks, I think that's exactly what I needed. Instead of 2017-05-31T16:13:26.252000+00:00Z I now have 2017-05-31T16:13:26.252000Z, which works for the API. Assuming that '252000' are milliseconds, right? And Z is UTC with no offsets, right? – Michael Jun 01 '17 at 13:45
  • 1
    Yes `%f` is for milliseconds (have a look at the [available directives for strftime](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior)). `Z` here is just a character that means Zulu/UTC, it won't do nothing to the datetime, therefore you will have to first make sure that the datetime is in the Zulu/UTC timezone before doing the `strftime`. You should be fine for the two cases you described. FYI: if you have to deal with timezones have a look at the [pytz package](https://pypi.python.org/pypi/pytz). – Paco H. Jun 01 '17 at 14:27
  • The datetime coming from the bigquery record is UTC with no offset so should be good. Thanks again. – Michael Jun 01 '17 at 14:57