Source

pythonwise / timeat

Full commit
#!/usr/bin/env python
# Small mash between Google maps API and earthtools API to get the current time
# at a given location

from urllib import urlopen, urlencode
import json
from xml.etree.cElementTree import iterparse

google_key = (
    'your-google-key-goes-here'
)


def timeat(location):
    query = urlencode([('q', location), ('key', google_key)])
    url = 'http://maps.google.com/maps/geo?{}'.format(query)
    try:
        # Sadly, sometimes google sends request that can't be encoded in utf-8
        location = json.load(urlopen(url))
    except UnicodeDecodeError:
        return

    if location['Status']['code'] != 200:
        return

    for placemark in location['Placemark']:
        lng, lat, h = placemark['Point']['coordinates']
        place = placemark['address']
        url = 'http://www.earthtools.org/timezone/%s/%s' % (lat, lng)
        for event, element in iterparse(urlopen(url)):
            if element.tag == 'localtime':
                yield place, element.text
                break


def main(argv=None):
    import sys
    from argparse import ArgumentParser

    argv = argv or sys.argv

    parser = ArgumentParser()
    parser.add_argument('location', help='location to get time at')
    args = parser.parse_args(argv[1:])

    try:
        matches = list(timeat(args.location))
        if not matches:
            raise SystemExit(
                'error: cannot find time for `{}`'.format(args.location))

        for addr, time in matches:
            print('{}: {}'.format(addr, time))
    except IOError as e:
        raise SystemExit('error: {}'.format(e))

if __name__ == '__main__':
    main()