Isoraqathedh

timezones.py

Jan 25th, 2014
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.79 KB | None | 0 0
  1. # Timezone.py
  2. # A local timezone location device
  3. # Integrates with Autohotkey
  4.  
  5. import json
  6. import urllib.request
  7. import time
  8. import datetime
  9. import argparse
  10. import configparser
  11.  
  12. # Global variables
  13. outputFile = r"\\psf\Home\Documents\AutoHotkey\_Main.ini"
  14.  
  15. # Incoming parameters
  16. cmdparse = argparse.ArgumentParser()
  17. cmdparse.add_argument("requestedLocation")
  18.  
  19. # Config file
  20. config = configparser.ConfigParser()
  21. config.read(outputFile)
  22.  
  23. # Make the urls
  24. # API format:
  25. # http://maps.googleapis.com/maps/api/geocode/json?address=<<query>>&sensor=false
  26. # https://maps.googleapis.com/maps/api/timezone/json?location=<<lat>>,<<long>>&timestamp=<<UNIX timestamp>>&sensor=false
  27. args = vars(cmdparse.parse_args())
  28. requestedLocation = args['requestedLocation'].replace(" ", "%20")
  29. MapsAPIURL = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false".format(requestedLocation)
  30. currentTime = time.time()
  31.  
  32. class PoorDataException(Exception):
  33.     pass
  34.  
  35. try:
  36.     # shoot off a request to maps api to geocode
  37.     with urllib.request.urlopen(MapsAPIURL) as request:
  38.         print("Getting data from Google Maps...")
  39.         response = request.read().decode('utf-8')
  40.         # Maps API outputs JSON; use JSON parser in Python to parse into python dictionaries
  41.         data = json.loads(response)
  42.         if data['status'] == "OK":
  43.             # extract the information off of that
  44.             actualPlaceFound = data['results'][0]["formatted_address"]
  45.             parsedCoords = (data['results'][0]['geometry']['location']["lat"], data['results'][0]['geometry']['location']["lng"])
  46.             print("Coordinate data received, lat = {0[0]}, lng = {0[1]}".format(parsedCoords))
  47.         else:
  48.             print("Error occured in trying to get coordinates: {0}".format(data["status"]))
  49.             raise PoorDataException("Maps", data["status"])
  50.     # --------
  51.     # Form the API URL:
  52.     # https://maps.googleapis.com/maps/api/timezone/json?location=<<lat>>,<<long>>&timestamp=<<UNIX timestamp>>&sensor=false
  53.     timeZoneURL = "https://maps.googleapis.com/maps/api/timezone/json?location={0[0]},{0[1]}&timestamp={1}&sensor=false".format(parsedCoords, currentTime)
  54.    
  55.     # shoot it off to timezone api
  56.     with urllib.request.urlopen(timeZoneURL) as request:
  57.         print("Getting timezone information...")
  58.         # Most of the operations here is the same as above.
  59.         response = request.read().decode('utf-8')
  60.         data = json.loads(response)
  61.         if data["status"] == "OK":
  62.             # form a timezone class – one-use, so it has got to be constant, hence the default
  63.             # implementation should do fine.
  64.             print("Timezone data received, tz = {0[rawOffset]}, dst = {0[dstOffset]}".format(data))
  65.             ordinaryTimeZone = datetime.timedelta(seconds=data["rawOffset"])
  66.             dstCorrection    = datetime.timedelta(seconds=data["dstOffset"])
  67.             locationTimezone = datetime.timezone(ordinaryTimeZone + dstCorrection, data["timeZoneName"])
  68.             print(locationTimezone)
  69.         else:
  70.             print("Error occured in trying to get time zone: {0}".format(data["status"]))
  71.             raise PoorDataException("Time Zone", data["status"])
  72.     # --------
  73.     # Now build the time format and chuck it to the output file
  74.     locationDateTime = datetime.datetime.fromtimestamp(currentTime, tz=locationTimezone)
  75.     formatted = locationDateTime.strftime("It is now %d.%m.%Y %H:%M:%S.%f in {0} running in %Z".format(actualPlaceFound))
  76.     print(formatted)
  77.     config['local time'] = {
  78.         'message': formatted,
  79.         'error': "none"
  80.     }
  81. except urllib.request.URLError: # The Internet is out!
  82.     print("No internet connection")
  83.     config['local time'] = {
  84.         'message': "",
  85.         'error': "No internet connection"
  86.     }
  87. except PoorDataException as e: # The API says you did something wrong!
  88.     config['local time'] = {
  89.         'message': "",
  90.         'error': "{0[1]} in {0[0]}".format(e.args)
  91.     }
  92. finally:
  93.     # write to config file. AHK will take care of the rest
  94.     with open(outputFile, 'w') as writeTarget: config.write(writeTarget)
Advertisement
Add Comment
Please, Sign In to add comment