【问题标题】:api data directly insert into PostgreSQL database with pythonapi数据直接用python插入PostgreSQL数据库
【发布时间】:2019-03-04 16:22:50
【问题描述】:

main.py

import json, urllib.request, requests
import psycopg2
from psycopg2.extras import execute_values


# Retrieve Json Data from Within API

url = "https://datahead.herokuapp.com/api/employeers/"
response = urllib.request.urlopen(url)
data = json.loads(response.read())


# ***** connect to the db *******
try:
    conn = psycopg2.connect("dbname='datahead' user='postgres' host='localhost' password='datahead'")
except:
    print("I am unable to connect to the database")

# cursor
cur = conn.cursor()

fields = [
    'id', #integer
    'name', #varchar
    'log_date', #date
    'log_time', #timestamp
    'login', #timestamp
    'logout' #timestamp
]

for item in data:
    my_data = [item[field] for field in fields]
    insert_query = "INSERT INTO employee VALUES (%s, %s, %s, %s, %s, %s)"
    cur.execute(insert_query, tuple(my_data))
    conn.commit()

# close the cursor
cur.close()

# close the connection
conn.close()

请访问我的api数据格式https://datahead.herokuapp.com/api/employeers/

它会改变这里的时间戳类型,如果是的话,我必须使用哪种数据类型? 第 56 行发生了什么?

【问题讨论】:

    标签: json database python-3.x postgresql


    【解决方案1】:

    我认为 login_time 在 PostgresSQL 中应该是 time without time zone 类型。

    但您最好使用timestamp with time zone 一起表示日期和时间。

    【讨论】:

    • 在我的登录、注销和 log_time 中,我使用了“没有时区的时间戳”,在这种情况下,我只想代表我的时间,这就是为什么没有使用时区并且不起作用的原因。
    • i.stack.imgur.com/KUC7z.png 请访问此图片,如果我使用时区,那么我可能无法计算。
    • 您上一条评论中的英文太少,我无法理解。另外,文字比图片好。
    • 是的,我已经解决了。必须使用那里的时间而不是时间戳。谢谢@Laurenz Albe
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多