yunaranyancat
yunaranyancat

Reputation: 131

Unknown spaces in output of python script after postgresql database query

I am trying to execute a query from postgresql database using the psycopg2, but my problem here is the output I get contains unknown spaces,

Here is my code:

#!/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()

What I get;

output contains spaces

What I need;

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

My problem here is;

Unknown spaces coming out from the output

Upvotes: 2

Views: 201

Answers (1)

Vao Tsun
Vao Tsun

Reputation: 51599

maybe spaces are known? try changing to

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

to get rows with unknown spaces, run:

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

or on other columns

Upvotes: 2

Related Questions