# coding: utf-8
#!/usr/bin/python
import urllib2
import json
import time
import os
import pandas as pd
#os.environ['TZ'] = 'Europe/Zurich'
#time.tzset()
# Given a target dictionary, look for keys in a list of keys to keep in the root of another nested dictionary
def addToFlatDict(mydict, root, keep_list):
for k in root.keys():
if k in keep_list :
mydict[k] = root[k]
# Write a new csv file with headers from an input pandas DataFrame if the file does not exist. If the file exists append data as new rows.
def appendDFToCSV_void(df, csvFilePath, sep=","):
import os
if not os.path.isfile(csvFilePath):
df.to_csv(csvFilePath, mode='a', index=False, sep=sep)
elif len(df.columns) != len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns):
raise Exception("Columns do not match!! Dataframe has " + str(len(df.columns)) + " columns. CSV file has " + str(len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns)) + " columns.")
elif not (df.columns == pd.read_csv(csvFilePath, nrows=1, sep=sep).columns).all():
raise Exception("Columns and column order of dataframe and csv file do not match!!")
else:
df.to_csv(csvFilePath, mode='a', index=False, sep=sep, header=False)
# Get the weather information as a json file
f = urllib2.urlopen('http://api.wunderground.com/api/'+apikey+'/geolookup/conditions/forecast/q/46.94809341,7.44744301.json')
# Write out the full response of the API call as a json file
json_string = f.read()
parsed_json = json.loads(json_string)
obs_time = parsed_json['current_observation']['observation_epoch']
with open('weather'+time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(float(obs_time)))+'.json', 'w') as file:
file.write(json_string)
file.close()
# Define a dictionary of field that we want to keep.
mydict = dict()
addToFlatDict(mydict, parsed_json['current_observation'], ['temp_c', 'wind_kph', 'wind_gust_kph', 'local_epoch', 'wind_degrees', 'dewpoint_c', 'precip_1hr_metric', 'precip_today_metric'] )
addToFlatDict(mydict, parsed_json['current_observation']['observation_location'], ['latitude', 'longitude'] )
# Turn the dictionary into a DataFrame and extract time fields for easier joins further downstream
df = pd.DataFrame(mydict, index=[0])
df['observation_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(obs_time)))
# Write the DataFrame to disk as a csv file
appendDFToCSV_void(df, 'weather'+time.strftime('%Y-%m-%d', time.localtime(float(obs_time)))+'.csv')
f.close()