In [ ]:
import psycopg2
import csv

try:
   connection = psycopg2.connect(user="username",
                                  password="password",
                                  host="IP Address",
                                  port="Port Num",
                                  database="DB Name")
   cursor = connection.cursor()

   postgreSQL_select_Query = "select _users.name from users left join _users on _users.id = users.id where COALESCE(users.login_at, users.created_at) < now()::date - 60"

   cursor.execute(postgreSQL_select_Query)

   naughty_users = cursor.fetchall() 
  
   with open('users.csv','w') as csvfile: 
       for row in naughty_users:
           writer = csv.writer(csvfile)
           writer.writerow(row[0])          

csvfile.close()

except (Exception, psycopg2.Error) as error :
    print ("Error while fetching data from PostgreSQL", error)

finally:
    #closing database connection.
    if(connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")