postgresql数据库查询后python脚本输出中的未知空格

时间:2017-05-03 07:27:40

标签: python postgresql python-2.x psycopg2

我正在尝试使用psycopg2从postgresql数据库执行查询,但我的问题是我得到的输出包含未知空格,

这是我的代码:

#!/usr/bin/python2.6
import pyscopg2
import datetime
import sys

list_site_id = []
if sys.argv[3] == '-site':
    for i in sys.argv[4:]:
         list_site_id.append(i)
else:
    print "Wrong parameter"

start_date_time = str(datetime.datetime.fromtimestamp(int(sys.argv[1])//1000.0))
end_date_time = str(datetime.datetime.fromtimestamp(int(sys.argv[2])//1000.0))

query = """
SELECT site,cnetworkdate,count(size) as active_al,new_al_name
FROM al_history
WHERE status="OLD" and group_al="PAN" and cnetworkdate >= %s and cnetworkdate >= %s and site = %s

conn = psycopg2.connect(database = "le_database", user = "le_user", password = "le_password"

cur = conn.cur()

for site_id in list_site_id:
    cur.execute(query,(start_date_time, end_date_time, site_id))
    rows = cur.fetchall()
    print "SITEID;TIMESTAMP;ACTIVE-ALARMS;REMARK
    for row in rows:
        print row[0],";",row[1],";",row[2],";",row[3]

conn.close()

我得到了什么;

output contains spaces

我需要什么;

SITEID;TIMESTAMP;ACTIVE-ALARMS;REMARK
LIPO;2017-05-02 21:29:31;1;LIPOME_1 down
LIPO;2017-05-02 21:29:31;1;LIPOME_3 down
LIPO;2017-05-02 21:29:31;1;LIPOME_2 down

我的问题是;

  

输出中出现未知空格

1 个答案:

答案 0 :(得分:2)

也许空间已知?尝试改为

SELECT trim(site),trim(cnetworkdate),count(size) as active_al,trim(new_al_name)

获取包含未知空格的行,运行:

SELECT site,length(site),replace(site,' ','*') 
from al_history where length(site) > length(trim(site))

或其他专栏