Advertisement
hd1

hd1/zipcode2tz

hd1
May 21st, 2015
473
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. def timezone():
  2.     code = request.args['q'].decode('utf-8')
  3.     logging.debug('Searching for {0}'.format(code))
  4.     url = 'http://www.boutell.com/zipcodes/zipcode.zip'
  5.     with tempfile.NamedTemporaryFile(prefix='usps', suffix='.zip') as out:
  6.         content = requests.get(url).content
  7.         out.write(content)
  8.         with zipfile.ZipFile(out) as zipfp:
  9.             zips = zipfp.read('zipcode.csv')
  10.             codes = StringIO()
  11.             codes.write(os.linesep.join([s for s in zips.splitlines() if s.strip()]))
  12.             codes.seek(0)
  13.             zipreader = csv.DictReader(codes, fieldnames = ["zip","city","state","latitude","longitude","timezone","dst"])
  14.             for line in zipreader:
  15.                 logging.debug('examining postal code {0}'.format(line['zip']))
  16.                 if line['zip'] == code:
  17.                     return Response(__lookuptimezone(line), mimetype='text/plain')
  18.  
  19. def __lookuptimezone(line):
  20.     if line['timezone'].endswith('5') and line['dst'] == '1':
  21.         return 'EST5EDT'
  22.     elif line['timezone'].endswith('5') and line['dst'] == '0':
  23.         return 'EST5'
  24.     elif line['timezone'].endswith('6') and line['dst'] == '1':
  25.         return 'CST6CDT'
  26.     elif line['timezone'].endswith('6') and line['dst'] == '0':
  27.         return 'CST6'
  28.     elif line['timezone'].endswith('7') and line['dst'] == '1':
  29.         return 'MST7MDT'
  30.     elif line['timezone'].endswith('7') and line['dst'] == '0':
  31.         return 'MST7'
  32.     elif line['timezone'].endswith('8') and line['dst'] == '1':
  33.         return 'PST8PDT'
  34.     elif line['timezone'].endswith('8') and line['dst'] == '0':
  35.         return 'PST8'
  36.     raise Exception, 'Invalid zipcdoe {0}'.format(line)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement