简体   繁体   中英

TypeError: an integer is required on my python script

I'm doing a python code that:

  • Take data from an API
  • parse the data
  • build a query and send it to my PGadmin database

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM