Advertisement
J2897

Get OpenWeather forecast

May 15th, 2024
948
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. import requests
  2. import datetime
  3.  
  4. # The name of the city you want to get the weather for
  5. city_name = "Manchester"
  6. #city_name = "Manchester,England,GB"
  7. #city_name = "Manchester,New Hampshire,US"
  8. #city_name = "Manchester,NH,US"
  9.  
  10. # Make the API request
  11. response = requests.get(f"http://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={OPENWEATHERMAP_KEY}")
  12.  
  13. # Check if the request was successful
  14. if response.status_code == 200:
  15.     # Parse the JSON data
  16.     data = response.json()
  17.  
  18.     # Convert timezone from seconds to hours and minutes
  19.     timezone_hours = data["timezone"] // 3600
  20.     timezone_minutes = (data["timezone"] % 3600) // 60
  21.     timezone_str = f"GMT{'+' if timezone_hours >= 0 else ''}{timezone_hours}:{timezone_minutes:02d}"
  22.  
  23.     # Print the weather data in a nicely formatted way
  24.     print("City: {}, ({})".format(data["name"], data["sys"]["country"]))
  25.     print("ID: {}".format(data["id"]))
  26.     print("Coordinates: ({}, {})".format(data["coord"]["lon"], data["coord"]["lat"]))
  27.     print("Weather: {}".format(data["weather"][0]["description"]))
  28.     print("Temperature: {:.2f}°C".format(data["main"]["temp"] - 273.15))
  29.     print("Feels like: {:.2f}°C".format(data["main"]["feels_like"] - 273.15))
  30.     print("Minimum temperature: {:.2f}°C".format(data["main"]["temp_min"] - 273.15))
  31.     print("Maximum temperature: {:.2f}°C".format(data["main"]["temp_max"] - 273.15))
  32.     print("Pressure: {} hPa".format(data["main"]["pressure"]))
  33.     print("Humidity: {}%".format(data["main"]["humidity"]))
  34.     print("Visibility: {} m".format(data["visibility"]))
  35.     print("Wind speed: {} m/s".format(data["wind"]["speed"]))
  36.     print("Wind direction: {}°".format(data["wind"]["deg"]))
  37.     print("Clouds: {}%".format(data["clouds"]["all"]))
  38.     print("Sunrise: {}".format(datetime.datetime.fromtimestamp(data["sys"]["sunrise"])))
  39.     print("Sunset: {}".format(datetime.datetime.fromtimestamp(data["sys"]["sunset"])))
  40.     #print("Timezone: {}".format(data["timezone"]))
  41.     print("Timezone: {}".format(timezone_str))
  42. else:
  43.     # Print an error message
  44.     print(f"Error: {response.status_code}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement