-
Notifications
You must be signed in to change notification settings - Fork 58
Closed as not planned
@sydney2711
Description
import requests
import csv
from datetime import datetime
import os
API_KEY = "dc2673cc0ef248daa38204655252306"
def get_weather_data(api_key, location="Ormeau"):
"""
Fetch current weather data from WeatherAPI.com
Args:
api_key (str): Your WeatherAPI.com API key
location (str): City name (default: Brisbane)
Returns:
dict: Dictionary containing temperature and humidity data with timestamp
"""
base_url = "http://api.weatherapi.com/v1/current.json"
params = {
'key': api_key,
'q': location,
'aqi': 'no' # We don't need air quality data
}
try:
response = requests.get(base_url, params=params)
response.raise_for_status() # Raise an exception for HTTP errors
data = response.json()
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Extract relevant weather data
weather_info = {
'timestamp': current_time,
'location': f"{data['location']['name']}, {data['location']['country']}",
'temperature_c': data['current']['temp_c'],
'temperature_f': data['current']['temp_f'],
'humidity': data['current']['humidity'],
'condition': data['current']['condition']['text'],
'last_updated': data['current']['last_updated']
}
return weather_info
except requests.exceptions.RequestException as e:
print(f"Error fetching weather data: {e}")
return None
def save_to_csv(data, filename="brisbane_weather.csv"):
"""
Save weather data to CSV file, creating header if file doesn't exist
Args:
data (dict): Weather data to save
filename (str): CSV filename (default: brisbane_weather.csv)
"""
file_exists = os.path.isfile(filename)
try:
with open(filename, mode='a', newline='') as csvfile:
fieldnames = ['timestamp', 'location', 'temperature_c', 'temperature_f',
'humidity', 'condition', 'last_updated']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not file_exists:
writer.writeheader() # Write header only if file doesn't exist
writer.writerow(data)
print(f"Weather data successfully saved to {filename}")
except Exception as e:
print(f"Error saving to CSV: {e}")
weather_data = get_weather_data(API_KEY)
save_to_csv(weather_data)
Metadata
Metadata
Assignees
Labels
No labels