Advertisement
icarussiano

API weather

Mar 22nd, 2024 (edited)
651
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. import requests
  2. import datetime
  3. import os
  4.  
  5. def nome_fase_lunare(moon_phase_value):
  6.     if moon_phase_value == 0 or moon_phase_value == 1:
  7.         return 'luna nuova'
  8.     elif moon_phase_value == 0.25:
  9.         return 'primo quarto'
  10.     elif moon_phase_value == 0.5:
  11.         return 'luna piena'
  12.     elif moon_phase_value == 0.75:
  13.         return 'ultimo quarto'
  14.     elif 0 < moon_phase_value < 0.25:
  15.         return 'crescente'
  16.     elif 0.25 < moon_phase_value < 0.5:
  17.         return 'gibbosa crescente'
  18.     elif 0.5 < moon_phase_value < 0.75:
  19.         return 'gibbosa calante'
  20.     elif 0.75 < moon_phase_value < 1:
  21.         return 'calante'
  22.     else:
  23.         return 'Errore: valore non valido'
  24.  
  25. def get_weather_data(city, state, api_key):
  26.     url = f"https://api.openweathermap.org/geo/1.0/direct?q={city},{state}&appid={api_key}"
  27.     response = requests.get(url)
  28.     data = response.json()
  29.     lat, lon = data[0]['lat'], data[0]['lon']
  30.     url = f"https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&appid={api_key}&units=metric"
  31.     response = requests.get(url)
  32.     data = response.json()
  33.     sunrise = datetime.datetime.fromtimestamp(data['daily'][0]['sunrise'])
  34.     sunset = datetime.datetime.fromtimestamp(data['daily'][0]['sunset'])
  35.     temperature = data['daily'][1]['temp']
  36.     moon_phase = data['daily'][0]['moon_phase']
  37.     weather = data['daily'][0]['weather'][0]['description']
  38.     return sunrise, sunset, temperature, moon_phase, weather
  39.  
  40. api_key = os.getenv('WEATHER_API_KEY')
  41. city = input("Scrivi la tua cittò: ")
  42. state = input("Scrivi il tuo Stato(ISO 3166. es. ITA): ")
  43.  
  44. sunrise, sunset, temperature, moon_phase, weather = get_weather_data(city, state, api_key)
  45. print(f"Fase lunare: {nome_fase_lunare(moon_phase)}")
  46. temperature_str = ', '.join(f"{k}: {v}°C" for k, v in temperature.items())
  47. print(f"Temperature: {temperature_str}")
  48. print(f"Alba: {sunrise: %D %H:%M:%S}")
  49. print(f"Tramonto: {sunset: %D %H:%M:%S}")
  50. print(f"Tempo: {weather}")
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement