Last active
May 18, 2017 07:54
-
-
Save champierre/d01c7019dfece6142220600a0b3fc717 to your computer and use it in GitHub Desktop.
Sample code to get weather info from https://developer.worldweatheronline.com/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'uri' | |
require 'json' | |
require 'byebug' | |
require 'csv' | |
API_KEY = "xxxx" | |
# query by lat and lng | |
# 35.443708,139.638026 is the lat and lng of yokohama city hall | |
# CSV Output Example | |
# | |
# 2016-01-01,12,7,Sunny,1026,41 | |
# 2016-01-02,18,4,Sunny,1022,53 | |
# 2016-01-03,17,10,Sunny,1017,48 | |
# 2016-01-04,19,12,Sunny,1014,63 | |
# ... | |
dates = [ | |
{start: '2016-01-01', end: '2016-01-31'}, | |
{start: '2016-02-01', end: '2016-02-29'}, | |
{start: '2016-03-01', end: '2016-03-31'}, | |
{start: '2016-04-01', end: '2016-04-30'}, | |
{start: '2016-05-01', end: '2016-05-31'}, | |
{start: '2016-06-01', end: '2016-06-30'}, | |
{start: '2016-07-01', end: '2016-07-31'}, | |
{start: '2016-08-01', end: '2016-08-31'}, | |
{start: '2016-09-01', end: '2016-09-30'}, | |
{start: '2016-10-01', end: '2016-10-31'}, | |
{start: '2016-11-01', end: '2016-11-30'}, | |
{start: '2016-12-01', end: '2016-12-31'}, | |
] | |
csv = CSV.generate do |csv| | |
dates.each do |date| | |
start_date = date[:start] | |
end_date = date[:end] | |
url = "http://api.worldweatheronline.com/premium/v1/past-weather.ashx?key=#{API_KEY}&q=35.443708,139.638026&format=json&date=#{start_date}&enddate=#{end_date}" | |
uri = URI.parse(url) | |
json = Net::HTTP.get(uri) | |
result = JSON.parse(json) | |
weather_data = result['data']['weather'] | |
weather_data.each do |data| | |
weather_desc = data['hourly'][4]['weatherDesc'][0]['value'] | |
pressure = data['hourly'][4]['pressure'] | |
humidity = data['hourly'][4]['humidity'] | |
arr = [data['date'], data['maxtempC'], data['mintempC'], weather_desc, pressure, humidity] | |
csv << arr | |
end | |
end | |
end | |
File.open("weather.csv", 'w') do |file| | |
file.write(csv) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment