Skip to content

Instantly share code, notes, and snippets.

@jmsword
Created January 24, 2017 16:22
Show Gist options
  • Save jmsword/e980a73cfddf4a1714bfcd7e7f758764 to your computer and use it in GitHub Desktop.
Save jmsword/e980a73cfddf4a1714bfcd7e7f758764 to your computer and use it in GitHub Desktop.
temperature
import requests
import sqlite3 as lite
import time
import datetime
import collections
import pandas as pd
#Cities to analyze
cities = {"Los_Angeles": "34.0522,-118.2437",
"Miami": "25.7617,-80.1918",
"Salt_Lake_City": "40.7608,-111.8910",
"San_Francisco": "37.7749,-123.4194",
"Seattle": "47.6062,-122.3321",
}
#My api key
apiKey = '05733033ea7b4253bf6224ef6a919782/'
url = 'https://api.darksky.net/forecast/' + apiKey
#Day to stop collection data
end_date = datetime.datetime.now()
#Create and connect to weather database
con = lite.connect('weather.db')
cur = con.cursor()
#Create daily temperature table
cities.keys()
with con:
cur.execute('CREATE TABLE daily_temp ( day_of_reading INT, Los_Angeles REAL, Miami REAL, Salt_Lake_City REAL, San_Francisco REAL, Seattle REAL);')
#Set start date to collect 30 days of data
query_date = end_date - datetime.timedelta(days=30)
#Insert blank date rows to daily temperature table
with con:
while query_date < end_date:
cur.execute("INSERT INTO daily_temp(day_of_reading) VALUES (?)", (int(time.mktime(query_date.timetuple())),))
query_date += datetime.timedelta(days=1)
for k, v in cities.items():
query_date = end_date - datetime.timedelta(days=30)
while query_date < end_date:
r = requests.get(url + v + ',' + query_date.strftime('%Y-%m-%dT12:00:00'))
with con:
cur.execute('UPDATE daily_temp SET ' + k + ' = ' + str(r.json()['daily']['data'][0]['temperatureMax']) + ' WHERE day_of_reading = ' + str(time.mktime(query_date.timetuple())))
query_date += datetime.timedelta(days=1)
con.close()
#Analysis
con = lite.connect('weather.db')
cur = con.cursor()
df = pd.read_sql_query('SELECT * FROM daily_temp ORDER BY day_of_reading', con)
city_list = list(df.columns.values[1:])
for i in city_list:
max_temp = max(df[i])
min_temp = min(df[i])
avg_temp = df[i].mean()
temp_range = max_temp - min_temp
deviation = df[i].std()
print (str(i) + ": Max temp: " + str(max_temp) + ", Min temp: " + str(min_temp) + \
", Temp range: " + str(temp_range) + ', Avg temp: ' + str(avg_temp) + \
". Standard deviation: " + str(deviation))
month_change = collections.defaultdict(int)
for i in city_list:
temps = df[i].tolist()
temp_change = 0
for k,v in enumerate(temps):
if k < len(temps) - 1:
temp_change += abs(temps[k] - temps[k + 1])
month_change[i] = int(temp_change)
def keywithmaxval(d):
v = list(d.values())
k = list(d.keys())
return k[v.index(max(v))]
max_city = keywithmaxval(month_change)
print ("Max city: " + max_city)
print ("Month change: " + str(month_change[max_city]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment