Search code examples
pythondategoogle-apitimestampgoogle-fit

How can I get the date format for a date used to filter results in the google fit API in python?


I'm trying to do GET query using as reference the example offered by the documentation of the API of google for sessions documented here which is as follows:

curl --header "Authorization: Bearer ya29.1.yourtokenvalue" -X GET \
--header "Content-Type: application/json;encoding=utf-8" \
"https://www.googleapis.com/fitness/v1/users/me/sessions?startTime=2014-04-01T00:00:00.000Z&endTime=2014-04-30T23:59:59.999Z"

As you can see the date as the following format:

2014-04-01T00:00:00.000Z

I'm currently the building the date in python as follows: from datetime import datetime, timedelta

PREVIOUS_DAYS=1
end = datetime.now().replace(minute=0, second=0)
start = end_date - timedelta(days = PREVIOUS_DAYS)
end_date = datetime.fromtimestamp(end).astimezone().strftime('%Y-%m-%dT%H:%M:%S.')
start_date = datetime.fromtimestamp(start).astimezone().strftime('%Y-%m-%dT%H:%M:%S.')
print str(start_date)

I have not idea what does de T mean and I can't find anything about what I think are mili seconds at the end of the timestamp in the strftime documentation. I can also not find any information of it in the google API documentation so maybe this is just a standard I'm expected to know?


Solution

  • Looks like this is a standard format called ISO 8601. Python supports encoding any datetime object in this format using the isoformat function. The only difference you'll see is the "Z" postfix which means that the timezone is UTC. Python will use a different notation "+00:00" which is also acceptable by the standard.

    >>> from datetime import datetime, timezone
    >>> datetime.now(timezone.utc).isoformat()
    2014-04-01T00:00:00.000+00:00
    

    If you really want to keep the "Z" postfix, it's ok to manually strip off the "+00:00", and add a "Z", but I believe that won't be necessary.

    >>> from datetime import datetime, timezone
    >>> datetime.now(timezone.utc).isoformat()[:-6] + "Z"
    2014-04-01T00:00:00.000Z