Guest User

quickWeather.py

a guest
Sep 7th, 2018
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.98 KB | None | 0 0
  1. #! python3
  2. # quickWeather.py - Prints the weather for a location from the command line.
  3. #
  4. # This code is part of a list of corrections on reddit at:
  5. # https://www.reddit.com/r/inventwithpython/comments/8ykq1i/automate_the_boring_stuff_with_python_corrections/
  6. # -/u/JoseALerma
  7.  
  8. import json, requests, sys, shelve, datetime
  9.  
  10.  
  11. def getWeather(loc, apikey):
  12.     # Download the JSON data from OpenWeatherMap.org's API.
  13.     url = 'http://api.openweathermap.org/data/2.5/forecast?q=%s&APPID=%s' % (loc, apikey)
  14.     response = requests.get(url)
  15.     response.raise_for_status()
  16.  
  17.     # Load JSON data into a Python variable.
  18.     data = json.loads(response.text)
  19.  
  20.     now = datetime.datetime.now(tz=datetime.timezone.utc)
  21.     data["savedTime"] = now
  22.     return data
  23.  
  24.  
  25. # Compute location from command line arguments.
  26. if len(sys.argv) < 2:
  27.     print('Usage: P05_quickWeather.py city,country code')
  28.     sys.exit()
  29. location = ' '.join(sys.argv[1:])
  30.  
  31. # Get API Key from file
  32. with open("apikey.txt") as file:
  33.     apiKey = file.read()
  34.  
  35. # Open shelf to read data
  36. weatherShelf = shelve.open("weather")
  37.  
  38. # Download and save data to shelf
  39. if not list(weatherShelf.keys()):  # Shelf empty, download data
  40.     weatherShelf["data"] = getWeather(location, apiKey)
  41. else:
  42.     # Check for 10 minute interval between API requests
  43.     timeNow = datetime.datetime.now(tz=datetime.timezone.utc)
  44.     savedTime = weatherShelf["data"]["savedTime"]
  45.     timedelta = timeNow - savedTime
  46.     interval = datetime.timedelta(minutes=10)
  47.  
  48.     if timedelta < interval:
  49.         city = weatherShelf["data"]["city"]
  50.         print("RequestError: Need to wait %s minutes. Using saved data for: %s, %s" %
  51.               (round((interval - timedelta).total_seconds()/60, 2), city["name"], city["country"]))
  52.     else:
  53.         weatherShelf["data"] = getWeather(location, apiKey)
  54.  
  55. # Print weather descriptions
  56. w = weatherShelf["data"]['list']
  57. count = int(weatherShelf["data"]["cnt"])
  58.  
  59. # Print current weather
  60. currentDate = datetime.datetime.strptime(w[0]["dt_txt"][:10], '%Y-%m-%d')
  61. print('Current weather in %s:' % location)
  62. print(w[0]['weather'][0]['main'], '-', w[0]['weather'][0]['description'])
  63. tomorrowDate = currentDate + datetime.timedelta(days=1)
  64. dayAfterDate = currentDate + datetime.timedelta(days=2)
  65. print()
  66.  
  67. for i in range(1, count):
  68.     currentDate = datetime.datetime.strptime(w[i]["dt_txt"][:10], '%Y-%m-%d')
  69.     # If current date is greater than tomorrow date, print tomorrow weather
  70.     if currentDate > tomorrowDate:
  71.         print('Tomorrow:')
  72.         print(w[i]['weather'][0]['main'], '-', w[i]['weather'][0]['description'])
  73.         tomorrowDate = currentDate + datetime.timedelta(days=7)  # past the 5-day forecast
  74.         print()
  75.     # If current date is greater than day after date, print day after tomorrow weather
  76.     elif currentDate > dayAfterDate:
  77.         print('Day after tomorrow:')
  78.         print(w[i]['weather'][0]['main'], '-', w[i]['weather'][0]['description'])
  79.         break
  80.  
  81. weatherShelf.close()
Add Comment
Please, Sign In to add comment