def downloadData(self,nlat_start,nlat_end): '''downloadData(self,nlat_start,nlat_end) routine to download data by latitude grid point. nlat_start, nlat_end are the indexes of the desired latitude points (starting from 0 and ending in self.nlat) Done this way because takes a long time to download data, so in case some part of the data are missing, can add... saves downloaded data into DarkSky.csv''' import pandas as pd from forecastiopy import ForecastIO,FIODaily times = self.dates["time"].to_list() key = "43b5a6b6b264933c0cac096ee0900db4" df = pd.DataFrame() for lat in range(nlat_start,nlat_end): for lon in self.lons: for t in range(0, len(times)): OKflag = True try: forecast = ForecastIO.ForecastIO( key, latitude=lat, longitude=lon, time=times[t], exclude=["currently", "hourly"], ) daily = FIODaily.FIODaily(forecast) new_line_dict = daily.get() except: OKflag=False if OKflag: if df.empty: df = pd.DataFrame.from_dict(new_line_dict["data"]) df["time"] = times[t][0:10] df["lat"] = lat df["lon"] = lon else: df1 = pd.DataFrame.from_dict(new_line_dict["data"]) df1["time"] = times[t][0:10] df1["lat"] = lat df1["lon"] = lon df = pd.concat([df, df1], sort=True) print(lon, "out of ", self.nlons) print(lat,'out of ',nlat_start,'-',nlat_end) # if wants to save from scratch each iteration (recommended..): df.to_csv('DarkSky.csv')
def TomorrowWeather(apikey, nowLatitude, nowLongitude, selCity): global tomorrowList tomorrowList = [] # Start from tomorrow 00:00 selDate = datetime.datetime.now() + datetime.timedelta(days=1) startTime = datetime.datetime(selDate.year, selDate.month, selDate.day, 0).isoformat() fio = CallFIO(apikey, nowLatitude, nowLongitude, startTime) if fio.has_daily() is True: daily = FIODaily.FIODaily(fio) tomorrowList = daily.get()['data'] for num in range(len(tomorrowList)): for idx, item in enumerate(tomorrowList[num].items()): # Change timestamp to a readable time format if bool(re.findall('time', item[0], re.IGNORECASE)) == True: tomorrowList[num][ item[0]] = datetime.datetime.fromtimestamp( item[1]).strftime('%Y-%m-%d %H:%M:%S') index_value = tomorrowList[0].values() index_name = tomorrowList[0].keys() report = {'': list(index_name), 'Forecast': list(index_value)} df = pd.DataFrame(report, columns=['', 'Forecast']) outdir_LOG = "./Files/" + selCity + "/" if not os.path.exists(outdir_LOG): os.makedirs(outdir_LOG, exist_ok=True) nowTime = selDate.strftime('%Y%m%d') filename = outdir_LOG + nowTime + '.csv' if not os.path.exists(filename): df.to_csv(filename, index=False, encoding='utf-8-sig') else: df = pd.read_csv(filename) df['Forecast'] = list(index_value) df = df.rename(columns={'Unnamed: 0': ''}) df.to_csv(filename, index=False, encoding='utf-8-sig') return True else: return False
def YesterdayWeather(apikey, nowLatitude, nowLongitude, selCity): global yesterdayList yesterdayList = [] # Start from yesterday 00:00 selDate = datetime.datetime.now() - datetime.timedelta(days=1) startTime = datetime.datetime(selDate.year, selDate.month, selDate.day, 0).isoformat() fio = CallFIO(apikey, nowLatitude, nowLongitude, startTime) if fio.has_daily() is True: daily = FIODaily.FIODaily(fio) yesterdayList = daily.get()['data'] for num in range(len(yesterdayList)): for idx, item in enumerate(yesterdayList[num].items()): # Change timestamp to a readable time format if bool(re.findall('time', item[0], re.IGNORECASE)) == True: yesterdayList[num][ item[0]] = datetime.datetime.fromtimestamp( item[1]).strftime('%Y-%m-%d %H:%M:%S') index_value = yesterdayList[0].values() outdir_LOG = "./Files/" + selCity + "/" if not os.path.exists(outdir_LOG): os.makedirs(outdir_LOG, exist_ok=True) nowTime = selDate.strftime('%Y%m%d') filename = outdir_LOG + nowTime + '.csv' if not os.path.exists(filename): ctypes.windll.user32.MessageBoxW( 0, "No past forecast record for yesterday", "Warning!", 0) return False else: df = pd.read_csv(filename) df['Reality'] = list(index_value) df = df.rename(columns={'Unnamed: 0': ''}) df.to_csv(filename, index=False, encoding='utf-8-sig') return True else: return False
def check_for_freeze(self): if self._fio.has_daily(): daily = FIODaily.FIODaily(self._fio) for x in range(0, 14): try: tempMin = daily.get_day(x)["temperatureMin"] if float(tempMin) <= 32: fmt = "%m-%d-%Y" now_time = datetime.now( timezone('US/Eastern')) + timedelta(days=x) time = now_time.strftime( fmt) # + datetime.timedelta(days=x) #print(time) TEXT = "Hello GardeNet User,\n\nThe forecast for " + time + " shows that the temperature" \ " may reach " + str(tempMin) + " degrees. We suggest preparing your system for the " \ "freeze. \n\nRegards,\nGardeNet" Alert(TEXT) break except: pass
def __init__(self, *args, **kwargs): super(Forecast, self).__init__(*args, **kwargs) self.current_forecast = FIOCurrently.FIOCurrently(self) self.hourly_forecast = FIOHourly.FIOHourly(self) self.daily_forecast = FIODaily.FIODaily(self)
def get_max_temp(self): if self._fio.has_daily(): daily = FIODaily.FIODaily(self._fio) return daily.get_day(0)["temperatureMax"]
col_names.append("Max_5") col_names.append("Min_avg") col_names.append("Max_max") #Obtain and read in weather data through Python3 wrapper for Dark Sky API for i in range(len(cities)): fio = ForecastIO.ForecastIO(key, latitude = cities[i].get_lat(), longitude = cities[i].get_lon(), units= 'si' ) daily = FIODaily.FIODaily( fio ) for day in range(2, 7): val = daily.get( day ) cities[i].add_minmax( str(val[ "temperatureMin" ]), str(val[ "temperatureMax" ])) #Write to CSV util.print_as_csv(out_file_name, cities, col_names)