|
import requests |
|
from datetime import datetime, timedelta |
|
import pandas as pd |
|
|
|
|
|
class WeatherDataFetcher: |
|
def __init__(self, api_key): |
|
self.api_key = api_key |
|
|
|
def get_lat_lon(self, city_name): |
|
""" |
|
Fetches the latitude and longitude for a given city name. |
|
|
|
Parameters: |
|
- city_name: The name of the city (including state and country). |
|
|
|
Returns: |
|
- A tuple (latitude, longitude) if successful, None otherwise. |
|
""" |
|
url = f'http://api.openweathermap.org/geo/1.0/direct?q={city_name}&limit=1&appid={self.api_key}' |
|
try: |
|
response = requests.get(url) |
|
data = response.json() |
|
if data: |
|
return data[0]['lat'], data[0]['lon'] |
|
else: |
|
print('No geo data found') |
|
return None |
|
except Exception as e: |
|
print(f"Error fetching geo data: {e}") |
|
return None |
|
|
|
def fetch_weather_data(self, lat, lon, start_date, end_date): |
|
""" |
|
Fetches weather data for a given set of coordinates within a specified date range |
|
and adds latitude and longitude to the DataFrame. |
|
|
|
Parameters: |
|
- lat: Latitude of the location. |
|
- lon: Longitude of the location. |
|
- start_date: The start date as a datetime object. |
|
- end_date: The end date as a datetime object. |
|
|
|
Returns: |
|
- A pandas DataFrame containing the weather data along with latitude and longitude. |
|
""" |
|
daily_data_frames = [] |
|
current_date = start_date |
|
|
|
while current_date <= end_date: |
|
timestamp = int(datetime.timestamp(current_date)) |
|
url = f'https://history.openweathermap.org/data/2.5/history/city?lat={lat}&lon={lon}&type=hour&start={timestamp}&appid={self.api_key}' |
|
|
|
response = requests.get(url) |
|
if response.status_code == 200: |
|
data = response.json() |
|
if 'list' in data: |
|
df_day = pd.json_normalize(data['list']) |
|
|
|
df_day['latitude'] = lat |
|
df_day['longitude'] = lon |
|
df_day['date'] = current_date.strftime('%Y-%m-%d') |
|
daily_data_frames.append(df_day) |
|
else: |
|
print(f"No 'list' key found in data for {current_date.strftime('%Y-%m-%d')}") |
|
else: |
|
print(f"Failed to retrieve data for {current_date.strftime('%Y-%m-%d')} with status code {response.status_code}") |
|
|
|
current_date += timedelta(days=1) |
|
|
|
if daily_data_frames: |
|
df_all_days = pd.concat(daily_data_frames, ignore_index=True) |
|
return self.expand_weather_column(df_all_days) |
|
else: |
|
return pd.DataFrame() |
|
|
|
def expand_weather_column(self,df): |
|
|
|
if 'weather' in df.columns: |
|
|
|
df['weather_id'] = df['weather'].apply(lambda x: x[0]['id'] if x else None) |
|
df['weather_main'] = df['weather'].apply(lambda x: x[0]['main'] if x else None) |
|
df['weather_description'] = df['weather'].apply(lambda x: x[0]['description'] if x else None) |
|
df['weather_icon'] = df['weather'].apply(lambda x: x[0]['icon'] if x else None) |
|
|
|
|
|
df = df.drop('weather', axis=1) |
|
return df |
|
|
|
def fetch_weather_for_cities(self, cities, start_date, end_date): |
|
all_cities_weather_data = [] |
|
|
|
for city_name in cities: |
|
lat_lon = self.get_lat_lon(city_name) |
|
if lat_lon: |
|
lat, lon = lat_lon |
|
df_weather = self.fetch_weather_data(lat, lon, start_date, end_date) |
|
if not df_weather.empty: |
|
df_weather['city'] = city_name |
|
all_cities_weather_data.append(df_weather) |
|
else: |
|
print(f"No weather data retrieved for {city_name}.") |
|
else: |
|
print(f"Failed to get latitude and longitude for {city_name}.") |
|
|
|
if all_cities_weather_data: |
|
all_data_df = pd.concat(all_cities_weather_data, ignore_index=True) |
|
return all_data_df |
|
else: |
|
return pd.DataFrame() |
|
|
|
def save_to_csv(self, df, file_name): |
|
try: |
|
df.to_csv(file_name, index=False) |
|
print(f"Data successfully saved to {file_name}.") |
|
except Exception as e: |
|
print(f"Failed to save data to CSV. Error: {e}") |