Skip to content

Instantly share code, notes, and snippets.

@AO8
Last active December 18, 2019 22:58
Show Gist options
  • Save AO8/ed45de2c440f89794b9a489ad13a7fdf to your computer and use it in GitHub Desktop.
Save AO8/ed45de2c440f89794b9a489ad13a7fdf to your computer and use it in GitHub Desktop.
Check the weather with Python 3 and the Open Weather dot Org API.
# explore the Open Weather dot Org API at: https://openweathermap.org/api
from datetime import datetime
import requests
def main():
# app_id will be specific to personal Open Weather acccount, 60 API calls per hour max
APP_ID = "#YourAppId"
# get zip code from user
zip_code = input("Enter a 5-digit, US zip code: ").strip()
# &units=imperial ensures degrees Farenheit and miles per hour
url = f"https://api.openweathermap.org/data/2.5/weather?zip={zip_code},us&APPId={APP_ID}&units=imperial"
weather_data = get_weather_json(url)
display_results(weather_data)
def from_utc_to_local_hour(utc_timestamp, shift):
"""Open Weather's API provides a UTC timestamp.
This simple pure Python function converts the utc timestamp to local 12-hour time."""
utc_datetime = datetime.utcfromtimestamp(utc_timestamp + shift)
hour_min_24 = utc_datetime.strftime("%H:%M")
hour_min_12 = datetime.strptime(hour_min_24, "%H:%M")
return hour_min_12.strftime("%I:%M %p")
def get_weather_json(url):
"""Use Requests to grab json data from the Open Weather API"""
resp = requests.get(url)
data = resp.json()
return data # dict
def display_results(weath_dict):
print(f"Data for {weath_dict['name']} at Latitude {weath_dict['coord']['lat']}, Longitude {weath_dict['coord']['lon']}:")
print(f"\n\t- {get_conditions(weath_dict).capitalize()}") # conditions
print(f"\t- The temperature is {get_temperature(weath_dict)} degrees Farenheit") #temperature
print(f"\t- Wind speed of {get_wind(weath_dict)} miles per hour") # wind speed
print(f"\t- Feels like {get_feels_like(weath_dict)} degrees Farenheit") # feels like
print(f"\t- Sunrise: {get_sunrise(weath_dict)}") # sunrise
print(f"\t- Sunset: {get_sunset(weath_dict)}") # sunset
def get_conditions(weather_dict):
return weather_dict["weather"][0]["description"]
def get_temperature(weather_dict):
return weather_dict["main"]["temp"]
def get_wind(weather_dict):
return weather_dict["wind"]["speed"]
def get_feels_like(weather_dict):
return weather_dict["main"]["feels_like"]
def get_sunrise(weather_dict):
return from_utc_to_local_hour(weather_dict["sys"]["sunrise"], weather_dict["timezone"])
def get_sunset(weather_dict):
return from_utc_to_local_hour(weather_dict["sys"]["sunset"], weather_dict["timezone"])
# ...additional get functions can be easily created and added to display_results()
# by referencing https://openweathermap.org/current#current_JSON
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment