Skip to content

Instantly share code, notes, and snippets.

@Zylvian
Created November 3, 2018 16:30
Show Gist options
  • Save Zylvian/a6f78289469968f69749e4d104633b00 to your computer and use it in GitHub Desktop.
Save Zylvian/a6f78289469968f69749e4d104633b00 to your computer and use it in GitHub Desktop.
#pip install requests
import requests
#import shutil
import xml.etree.ElementTree as ET
from time import localtime, strftime
#pip install python-dateutil
import dateutil.parser
import datetime
#import matplotlib.pyplot as plt
import json
# Functional PNG API downloader.
"""
r2 = requests.get("https://api.met.no/weatherapi/weathericon/1.1/?symbol=5&content_type=image/png")
if response.status_code == 200:
with open("/Users/jovli/Desktop/sample3.png", 'wb') as f:
f.write(r2.content)
"""
# Bergen coordinates
LATITUDE = 60.38944
LONGITUDE = 5.33
request_string = "https://api.met.no/weatherapi/nowcast/0.9/?lat={lat}&lon={lon}".format(lat=LATITUDE, lon=LONGITUDE)
# Website data
response = requests.get(request_string)
# Gets the website data
root = ET.fromstring(response.content)
product = root[1]
time_data_list = [time.get('from') for time in product.iter('time')]
value_data_list = [float(precipitation.get('value')) for precipitation in product.iter('precipitation')]
# Gets from-time and rain-value in a tuple and appends it to a list.
weather_data = list()
for i, time in enumerate(product.findall('time')):
from_data = time.get('from')
for precipitation in time.iter('precipitation'): # time.find() by itself doesn't work.
value_data = float(precipitation.get('value'))
weather_data.append((from_data, value_data))
# Datetime
dt = datetime.datetime.now()
dt_time = dt.timestamp()
mins_from_now = list()
# If any rain period of rain with over 0.5 mm of rainfall starts within 2 hours, return True.
def raining():
for i,(from_data, value_data) in enumerate(weather_data):
from_dt = dateutil.parser.parse(from_data)
from_time = from_dt.timestamp()
diff = from_time - dt_time
diff = int(diff/60)
mins_from_now.append(diff)
if diff < 120 and value_data > 2:
return True
return False
def json_up():
output = {
"rain_bool":str(raining())
}
with open('ajaxJson.json', 'w') as outfile:
json.dump(output, outfile)
print("Success!")
json_up()
""" output = "{}. {} minutes from now it's gonna rain {} mm".format(i+1, diff, value_data)
print(output)
print(False)"""
"""
plt.plot(mins_from_now, value_data_list)
plt.show()"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment