Skip to content

Instantly share code, notes, and snippets.

@lecram
Created July 12, 2012 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lecram/3100051 to your computer and use it in GitHub Desktop.
Save lecram/3100051 to your computer and use it in GitHub Desktop.
Currency conversion.
#! /usr/bin/python
import urllib2
import json
import time
import sys
baseurl = "http://openexchangerates.org/api/latest.json"
key = "{{Your Open Exchange Rates App ID here!}}"
url = baseurl + "?app_id=" + key
try:
f = open("latest.json", "r")
exists = True
except IOError:
exists = False
except:
raise
valid = False
if exists:
raw = f.read()
data = json.loads(raw)
f.close()
if time.time() - data['timestamp'] < 3600:
valid = True
if not exists or not valid:
f = open("latest.json", "w")
s = urllib2.urlopen(url)
raw = s.read()
f.write(raw)
s.close()
f.close()
data = json.loads(raw)
if len(sys.argv) != 4:
print "usage: oer.py from to value"
else:
base, quotes, value = sys.argv[1:]
for quote in quotes.split(','):
result = float(value) * float(data['rates'][quote]) / float(data['rates'][base])
print "%.4f %s = %.4f %s" % (float(value), base, result, quote)
print time.strftime("Last update: %c.", time.localtime(int(data['timestamp'])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment