import requests from datetime import datetime, timedelta def get_weather_data(city, days, api_key): try: geo_url = f"http://api.openweathermap.org/geo/1.0/direct?q={city}&limit=1&appid={api_key}" geo_response = requests.get(geo_url).json() if not geo_response: return None lat, lon = geo_response[0]['lat'], geo_response[0]['lon'] url = f"http://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude=minutely,hourly&units=metric&appid={api_key}" response = requests.get(url).json() current = { 'temp': response['current']['temp'], 'weather': response['current']['weather'][0]['description'], 'humidity': response['current']['humidity'], 'wind_speed': response['current']['wind_speed'] } forecast = [] for i in range(min(days, len(response['daily']))): day = response['daily'][i] forecast.append({ 'date': datetime.fromtimestamp(day['dt']).strftime('%Y-%m-%d'), 'temp': day['temp']['day'], 'precipitation': day.get('rain', 0) + day.get('snow', 0), 'wind_speed': day['wind_speed'], 'weather': day['weather'][0]['main'] }) return {'current': current, 'forecast': forecast} except Exception as e: print(f"Error fetching weather data: {e}") return None