File size: 1,454 Bytes
54f6ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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