Skip to content

Instantly share code, notes, and snippets.

@hello-josh
Last active February 28, 2018 07:50
Show Gist options
  • Save hello-josh/38a2da1937bca7ca0012 to your computer and use it in GitHub Desktop.
Save hello-josh/38a2da1937bca7ca0012 to your computer and use it in GitHub Desktop.
Get a user's timezone on app engine based off of the Google Maps Time Zone API
import time
import json
from pytz.gae import pytz
from google.appengine.api import urlfetch
#: Preset object for America/New_York
EasternTz = pytz.timezone('America/New_York')
def user_timezone_from_latlong(lat_long=None):
"""Fetches a user's time zone based on their lat/long using the google maps time zone api
See https://developers.google.com/maps/documentation/timezone/intro
Example::
>>> import webapp2
>>> lat_long = webapp2.get_request().headers.get('X-Appengine-Citylatlong')
>>> tz = user_timezone_from_latlong(lat_long)
>>> print tz.tzname()
:param str lat_long: User's lat/long. Usually from the request header X-Appengine-Citylatlong
"""
if lat_long is None:
return EasternTz
unix_time = int(time.time())
url = "https://maps.googleapis.com/maps/api/timezone/json" \
"?location={lat_long}&timestamp={unix_time}&key={token}"
url = url.format(lat_long=lat_long, unix_time=unix_time,
token=config.google_server_application_api_key)
response = urlfetch.fetch(url)
if response.status_code >= 400:
raise Exception("Error fetching Time Zone info for {}: {}".format(
lat_long, response.content
))
zoneinfo = json.loads(response.content)
if zoneinfo['status'] != "OK":
raise Exception("{}".format(zoneinfo['error_message']))
return pytz.timezone(zoneinfo.get('timeZoneId'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment