Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Fetch current weather from openweathermap api and save it to a sqlite database
import sqlite3
import json
import urllib
import datetime
import calendar
WEATHER_DATA_URL = ',de&units=metric'
DB_PATH = ''
def get_data():
"""get weather data from openweathermap"""
response = urllib.urlopen(WEATHER_DATA_URL)
data = json.loads(
print data
temp = data['main']['temp']
pressure = data['main']['pressure']
temp_min = data['main']['temp_min']
temp_max = data['main']['temp_max']
humidity = data['main']['humidity']
wind_speed = data['wind']['speed']
wind_gust = data['wind']['gust']
except KeyError:
wind_gust = None
wind_deg = data['wind']['deg']
clouds = data['clouds']['all']
rain = data['rain']['3h']
except KeyError:
rain = None
snow = data['snow']['3h']
except KeyError:
snow = None
weather_id = data['weather'][0]['id']
sunrise = data['sys']['sunrise']
sunset = data['sys']['sunset']
return [temp, pressure, temp_min, temp_max, humidity, wind_speed, wind_gust, wind_deg, clouds, rain, snow,
weather_id, sunrise, sunset]
def save_data_to_db(data):
con = sqlite3.connect(DB_PATH)
con.isolation_level = None
cur = con.cursor()
query = '''INSERT INTO weather_data VALUES (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'''
cur.execute(query, tuple([] + data[:-2]))
def main():
data = get_data()
now = calendar.timegm(
#only save data after sunrise and before sunset
if data[-2] < now < data[-1]:
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.