I'm doing a python code that:
Here's my code:
# -*- coding: utf-8 -*-
import requests
import json
import datetime
import os
import psycopg2
from urlparse import urlparse
try:
conn = psycopg2.connect("dbname='tp_1' user='postgres' host='localhost' password='senha'")
except psycopg2.DatabaseError, ex:
print 'I am unable to connect the database: ' + str(ex)
cur = conn.cursor()
url = "https://www.mercadobitcoin.net/api/BTC/day-summary/2013/6/20/"
moeda = url.split('/')[4]
response = requests.get(url)
print("---------------------")
data = response.text
print(data)
print("---------------------")
parsed = json.loads(data)
opening = parsed["opening"]
closing = parsed["closing"]
lowest = parsed["lowest"]
highest = parsed["highest"]
volume = parsed["volume"]
quantity = parsed["quantity"]
amount = parsed["amount"]
avg_price = parsed["avg_price"]
date = parsed["date"]
print(opening)
print(closing)
print(lowest)
print(highest)
print(volume)
print(quantity)
print(amount)
print(avg_price)
print(date)
SQL = "INSERT INTO day_summary (id_day, data_day, opening, closing, lowest, highest ,volume,quantity, amount, avg_price ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
data = (1,datetime.date(date), opening, closing, lowest, highest, volume, quantity, amount, avg_price)
cur.execute(SQL, data)
conn.commit()
cur.close()
conn.close()
This is the outputs from my prints:
---------------------
{"date": "2013-06-20", "opening": 262.99999, "closing": 269.0, "lowest": 260.00002, "highest": 269.0, "volume": 7253.13363568, "quantity": 27.11390588, "amount": 28, "avg_price": 267.50604165}
---------------------
262.99999
269.0
260.00002
269.0
7253.13363568
27.11390588
28
267.50604165
2013-06-20
And here's my traceback:
Traceback (most recent call last):
File "dados_api_day.py", line 56, in <module>
data = (1,datetime.date(date), opening, closing, lowest, highest, volume, quantity, amount, avg_price)
TypeError: an integer is required
I am not being able to solve the problem. I hope I could make it clear enough, so you can help me! Thanks!
Got it working. It was caused by the date. In fact, when I parse the data from the URL, the date variable is UNICODE. What you need to do is convert it by doing:
your_new_date = datetime.datetime.strptime(date_that_you_want_to_convert, '%Y-%m-%d')
Hope it will help!