-
Notifications
You must be signed in to change notification settings - Fork 0
/
weather_forecast_2_json.py
67 lines (54 loc) · 2.57 KB
/
weather_forecast_2_json.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from datetime import date
from weather.weather import WeatherExtractor, WeatherApi
import pandas as pd
from weather_combined import Weather_combined
from weather_separate import Weather_separate
class Weather_forecast_2_json:
def __init__(self, we, file_name_combined, file_name_separate):
#self.wc = Weather_combined()
#self.ws = Weather_separate()
self._we = we
self._fc = open(file_name_combined, 'w')
self._fs = open(file_name_separate, 'w')
self._file_name_combined = file_name_combined
self._file_name_separate = file_name_separate
def __del__(self):
print 'Closing file %s' % self._file_name_combined
self._fc.close()
print 'Closing file %s' % self._file_name_separate
self._fs.close()
def fetch_forecast(self, from_date, to_date, city_elem):
base_dates = pd.date_range(from_date, to_date)
self._fetch_forecast_daterange(base_dates, city_elem)
def _print_data(self, weather_data):
for row in weather_data.iterrows():
# row is tuple (index, columns)
measure = row[1]
print "Measurement of %s at from %s for %s" % (measure['shortName'], measure['validDateTime'], measure['validityDateTime'])
for lat, lon, val in zip(measure['lats'], measure['lons'], measure['values']):
print "%f N %f S = %f" % (lat, lon, val)
def _fetch_forecast_daterange(self, base_dates, city_elem):
wc = Weather_combined()
ws = Weather_separate()
points = [{'lat': city_elem.Latitude, 'lon': city_elem.Longitude}]
for bd in base_dates:
base_date = bd.date()
base_date_plus_16 = (bd+16).date() # Forecase the next 16 days (probably only 8 present)
weather_data = self._we.get_forecast(base_date=base_date,
from_date=base_date, to_date=base_date_plus_16,
aggtime='hour', aggloc='points',
interp_points=points)
wc.add_city_weather_data(city_elem.City, weather_data)
ws.add_city_weather_data(city_elem.City, weather_data)
self._write_to_json(self._fc, wc)
self._write_to_json(self._fs, ws)
def _write_to_json(self, f, w):
d_arr = w.get_dict_values()
#print 'Total dict'
#print d_arr
for d in d_arr:
#print 'For dict'
#print d
pds = pd.Series(d)
json_str = pds.to_json(path_or_buf=None, orient='index', date_format='iso', date_unit='s')
print >> f, json_str