Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Timezone.py
- # A local timezone location device
- # Integrates with Autohotkey
- import json
- import urllib.request
- import time
- import datetime
- import argparse
- import configparser
- # Global variables
- outputFile = r"\\psf\Home\Documents\AutoHotkey\_Main.ini"
- # Incoming parameters
- cmdparse = argparse.ArgumentParser()
- cmdparse.add_argument("requestedLocation")
- # Config file
- config = configparser.ConfigParser()
- config.read(outputFile)
- # Make the urls
- # API format:
- # http://maps.googleapis.com/maps/api/geocode/json?address=<<query>>&sensor=false
- # https://maps.googleapis.com/maps/api/timezone/json?location=<<lat>>,<<long>>×tamp=<<UNIX timestamp>>&sensor=false
- args = vars(cmdparse.parse_args())
- requestedLocation = args['requestedLocation'].replace(" ", "%20")
- MapsAPIURL = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false".format(requestedLocation)
- currentTime = time.time()
- class PoorDataException(Exception):
- pass
- try:
- # shoot off a request to maps api to geocode
- with urllib.request.urlopen(MapsAPIURL) as request:
- print("Getting data from Google Maps...")
- response = request.read().decode('utf-8')
- # Maps API outputs JSON; use JSON parser in Python to parse into python dictionaries
- data = json.loads(response)
- if data['status'] == "OK":
- # extract the information off of that
- actualPlaceFound = data['results'][0]["formatted_address"]
- parsedCoords = (data['results'][0]['geometry']['location']["lat"], data['results'][0]['geometry']['location']["lng"])
- print("Coordinate data received, lat = {0[0]}, lng = {0[1]}".format(parsedCoords))
- else:
- print("Error occured in trying to get coordinates: {0}".format(data["status"]))
- raise PoorDataException("Maps", data["status"])
- # --------
- # Form the API URL:
- # https://maps.googleapis.com/maps/api/timezone/json?location=<<lat>>,<<long>>×tamp=<<UNIX timestamp>>&sensor=false
- timeZoneURL = "https://maps.googleapis.com/maps/api/timezone/json?location={0[0]},{0[1]}×tamp={1}&sensor=false".format(parsedCoords, currentTime)
- # shoot it off to timezone api
- with urllib.request.urlopen(timeZoneURL) as request:
- print("Getting timezone information...")
- # Most of the operations here is the same as above.
- response = request.read().decode('utf-8')
- data = json.loads(response)
- if data["status"] == "OK":
- # form a timezone class – one-use, so it has got to be constant, hence the default
- # implementation should do fine.
- print("Timezone data received, tz = {0[rawOffset]}, dst = {0[dstOffset]}".format(data))
- ordinaryTimeZone = datetime.timedelta(seconds=data["rawOffset"])
- dstCorrection = datetime.timedelta(seconds=data["dstOffset"])
- locationTimezone = datetime.timezone(ordinaryTimeZone + dstCorrection, data["timeZoneName"])
- print(locationTimezone)
- else:
- print("Error occured in trying to get time zone: {0}".format(data["status"]))
- raise PoorDataException("Time Zone", data["status"])
- # --------
- # Now build the time format and chuck it to the output file
- locationDateTime = datetime.datetime.fromtimestamp(currentTime, tz=locationTimezone)
- formatted = locationDateTime.strftime("It is now %d.%m.%Y %H:%M:%S.%f in {0} running in %Z".format(actualPlaceFound))
- print(formatted)
- config['local time'] = {
- 'message': formatted,
- 'error': "none"
- }
- except urllib.request.URLError: # The Internet is out!
- print("No internet connection")
- config['local time'] = {
- 'message': "",
- 'error': "No internet connection"
- }
- except PoorDataException as e: # The API says you did something wrong!
- config['local time'] = {
- 'message': "",
- 'error': "{0[1]} in {0[0]}".format(e.args)
- }
- finally:
- # write to config file. AHK will take care of the rest
- with open(outputFile, 'w') as writeTarget: config.write(writeTarget)
Advertisement
Add Comment
Please, Sign In to add comment