dschandra commited on
Commit
54f6ae2
·
verified ·
1 Parent(s): 6f1cc1c

Create weather_model.py

Browse files
Files changed (1) hide show
  1. weather_model.py +40 -0
weather_model.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from datetime import datetime, timedelta
3
+
4
+ def get_weather_data(city, days, api_key):
5
+ try:
6
+ # Geocode city to lat/lon
7
+ geo_url = f"http://api.openweathermap.org/geo/1.0/direct?q={city}&limit=1&appid={api_key}"
8
+ geo_response = requests.get(geo_url).json()
9
+ if not geo_response:
10
+ return None
11
+ lat, lon = geo_response[0]['lat'], geo_response[0]['lon']
12
+
13
+ # Fetch weather data
14
+ url = f"http://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude=minutely,hourly&units=metric&appid={api_key}"
15
+ response = requests.get(url).json()
16
+
17
+ # Current weather
18
+ current = {
19
+ 'temp': response['current']['temp'],
20
+ 'weather': response['current']['weather'][0]['description'],
21
+ 'humidity': response['current']['humidity'],
22
+ 'wind_speed': response['current']['wind_speed']
23
+ }
24
+
25
+ # Forecast
26
+ forecast = []
27
+ for i in range(min(days, len(response['daily']))):
28
+ day = response['daily'][i]
29
+ forecast.append({
30
+ 'date': datetime.fromtimestamp(day['dt']).strftime('%Y-%m-%d'),
31
+ 'temp': day['temp']['day'],
32
+ 'precipitation': day.get('rain', 0) + day.get('snow', 0),
33
+ 'wind_speed': day['wind_speed'],
34
+ 'weather': day['weather'][0]['main']
35
+ })
36
+
37
+ return {'current': current, 'forecast': forecast}
38
+ except Exception as e:
39
+ print(f"Error fetching weather data: {e}")
40
+ return None