Repository for Petra's work at ampli Jan-Feb 2019

util.py 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. from argparse import ArgumentTypeError
  2. import psycopg2 as pg
  3. from configparser import ConfigParser
  4. import pandas.io.sql as psql
  5. import pandas as p
  6. import datetime as dt
  7. import numpy as np
  8. from pprint import pprint
  9. def datevalid(d):
  10. try:
  11. return dt.datetime.strptime(d, "%Y-%m-%d")
  12. except ValueError:
  13. raise ArgumentTypeError("Invaid date: {}".format(d))
  14. def config(filename='database.ini', section='postgresql'):
  15. """Config parser from
  16. http://www.postgresqltutorial.com/postgresql-python/connect/"""
  17. # create a parser
  18. parser = ConfigParser()
  19. # read config file
  20. parser.read(filename)
  21. # get section, default to postgresql
  22. db = {}
  23. if parser.has_section(section):
  24. params = parser.items(section)
  25. for param in params:
  26. db[param[0]] = param[1]
  27. else:
  28. raise Exception(
  29. 'Section {0} not found in the {1} file'.format(section, filename))
  30. return db
  31. def getQuery(query, qparams=[], verbose = True):
  32. """
  33. Get single query
  34. """
  35. conn = False
  36. try:
  37. params = config()
  38. if verbose:
  39. print("Connecting to database")
  40. conn = pg.connect(**params)
  41. cur = conn.cursor()
  42. # Get table
  43. if verbose:
  44. print("Retrieving table")
  45. dataframe = psql.read_sql(query, conn, params=qparams)
  46. cur.close()
  47. if verbose:
  48. print("Table recieved")
  49. return dataframe
  50. except (Exception, pg.DatabaseError) as error:
  51. raise error
  52. finally:
  53. if conn is not False:
  54. conn.close()
  55. if verbose:
  56. print('Database connection closed')
  57. def pickleQuery(query, path, qparams=[]):
  58. dq = getQuery(query, qparams)
  59. dq.to_pickle(path)
  60. print("Table pickled")
  61. def gettemp(datestart, dateend, station, verbose = True):
  62. query = """
  63. SELECT record_no, station, temp_date, temp_date + temp_time AS temp_timestamp, tmax_c, tmin_c,
  64. tgmin, tmean, rhmean
  65. FROM weather.temperature_fact
  66. WHERE station = %(station)s AND
  67. temp_date >= to_date(%(datestart)s, 'yyyy-mm-dd') AND
  68. temp_date < to_date(%(dateend)s, 'yyyy-mm-dd')
  69. ORDER BY temp_date, temp_time;
  70. """
  71. pdict = {
  72. 'datestart': datestart,
  73. 'dateend': dateend,
  74. 'station': station
  75. }
  76. if verbose:
  77. print("Getting data with parameters:")
  78. pprint(pdict)
  79. qdf = getQuery(query, pdict, verbose)
  80. if verbose:
  81. print("converting")
  82. qdf.temp_date = p.to_datetime(qdf.temp_date)
  83. if verbose:
  84. print('Done')
  85. return qdf
  86. if __name__ == "__main__":
  87. dv = getQuery('SELECT version()').version[0]
  88. print('PostgreSQL database version:')
  89. print(dv)