json - api数据直接用python插入PostgreSQL数据库
问题描述
主文件
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行发生了什么?
解决方案
我认为login_time
应该是time without time zone
PostgresSQL 的类型。
但是你可能会更好地使用timestamp with time zone
一起表示日期和时间。
推荐阅读
- android - 标签图标在滑动时突出显示
- ios - 尝试使用 pod clean 命令更新 Xcode 中的 pod 文件时出错?
- oracle - 新增量后执行 PL/SQL 代码
- json - 如何使 CloudFormation 模板中的整个对象成为可选?
- asp.net-core - IHostedService.StopAsync 是否正在等待请求线程?
- xml - 使用 XSLT 解析 XML 属性
- git - 如何处理同一分支上的不同逻辑
- dialogflow-es - 如何在 Dialogflow 中强制隐式调用(谷歌操作)
- javascript - 将日期时间字符串更改为另一个时区
- redis - Redis地理空间,按时间查询