Created
July 12, 2012 18:41
-
-
Save lecram/3100051 to your computer and use it in GitHub Desktop.
Currency conversion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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