Python 3.x 在PostgreSQL中插入Python错误“17处或附近出现语法错误”

Python 3.x 在PostgreSQL中插入Python错误“17处或附近出现语法错误”,python-3.x,postgresql,psycopg2,Python 3.x,Postgresql,Psycopg2,我在用Python将数据插入PostgreSQL时遇到了问题,但向我展示了这个错误。错误: syntax error at or near "17" LINE 30: 2021-01-05 17:38:59) 下面是我的python代码。我已经在windows计算机上使用了psycopg2和Python3.7。非常感谢 try: dados = GetDatasClimaTempo() con = psycop

我在用Python将数据插入PostgreSQL时遇到了问题,但向我展示了这个错误。错误:

syntax error at or near "17"
LINE 30:                 2021-01-05 17:38:59)
下面是我的python代码。我已经在windows计算机上使用了psycopg2和Python3.7。非常感谢

try:
        dados = GetDatasClimaTempo()
        con = psycopg2.connect(host='localhost', database='banco_arduino', user='gabriel', password='password')
        cur = con.cursor()

        sql = f"""insert into estacao_app_registrometeorologico
                (temperaturaAmbiente, 
                radiacaoDifusa, 
                radiacaoGlobal,
                pressao, 
                altitudeReal, 
                indiceUltravioleta, 
                precipitacaoInstantanea, 
                precipitacaoAcumulada, 
                umidade, 
                velocidadeVento, 
                direcaoVento,
                anguloVento, 
                radiometroTermico, 
                timestamp)
                values 
                ({dados['temperatura']},
                {truncate(random.uniform(10.5, 100.5),2)},
                {truncate(random.uniform(10, 3000),2)},
                {dados['pressao']},
                {truncate(random.uniform(10.5, 100.5),2)},
                {truncate(random.uniform(1, 11),2)},
                {truncate(random.uniform(10.5, 100.5),2)},
                {truncate(random.uniform(1, 15),2)},
                {dados['umidade']},
                {dados['velocidadeVento']},
                {dados['direcaoVento']},
                {truncate(random.uniform(0, 360),2)},
                {truncate(random.uniform(10.5, 100.5),2)},
                {datetime.datetime.strptime(dados['timestamp'], '%Y-%m-%d %H:%M:%S')})"""

        
        cur.execute(sql)
        con.commit()
        cur.execute('select * from estacao_app_registrometeorologico')
        recset = cur.fetchall()
        for rec in recset:
            print (rec)
        con.close()
    except Exception as ex:
        print(ex)

简短的回答是将strtime的结果用单引号括起来:

        sql = f"""insert into estacao_app_registrometeorologico
                 ...
               '{datetime.datetime.strptime(dados['timestamp'], '%Y-%m-%d %H:%M:%S')}')"""

较长的答案是重写代码,根据发现的警告使用参数