# app.py import streamlit as st import requests import datetime import pytz import pandas as pd st.set_page_config(page_title="Live Weather Forecast", page_icon="☀️", layout="wide") # **REPLACE THIS WITH YOUR ACTUAL OPENWEATHERMAP API KEY** API_KEY = "http://api.openweathermap.org/data/2.5/forecast?id=524901&appid={API key}" # Get your API key from openweathermap.org def get_weather_data(city): base_url = "https://api.openweathermap.org/data/2.5/weather" params = {"q": city, "appid": API_KEY, "units": "metric"} try: response = requests.get(base_url, params=params) response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) weather_data = response.json() return weather_data except requests.exceptions.RequestException as e: st.error(f"Error fetching weather data: {e}") return None def format_time(timestamp, timezone_str): try: timezone = pytz.timezone(timezone_str) dt_object = datetime.datetime.fromtimestamp(timestamp, tz=timezone) return dt_object.strftime("%I:%M %p %Z") # 12-hour format with timezone except Exception as e: # pytz errors st.error(f"Error formatting time: {e}") return "N/A" st.title("Live Weather Forecast") city = st.text_input("Enter a city:", "London") if city: weather_data = get_weather_data(city) if weather_data: col1, col2, col3 = st.columns(3) with col1: st.metric("Temperature", f"{weather_data['main']['temp']}°C") st.metric("Feels Like", f"{weather_data['main']['feels_like']}°C") st.metric("Humidity", f"{weather_data['main']['humidity']}%") with col2: st.metric("Wind Speed", f"{weather_data['wind']['speed']} m/s") try: st.metric("Wind Gust", f"{weather_data['wind']['gust']} m/s") except KeyError: st.metric("Wind Gust", "N/A") st.metric("Pressure", f"{weather_data['main']['pressure']} hPa") with col3: timezone_str = weather_data.get("timezone", "UTC") / 3600 # Timezone offset in hours try: sunrise_time = format_time(weather_data['sys']['sunrise'], "Etc/GMT" + str(int(-timezone_str))) sunset_time = format_time(weather_data['sys']['sunset'], "Etc/GMT" + str(int(-timezone_str))) st.metric("Sunrise", sunrise_time) st.metric("Sunset", sunset_time) except KeyError: st.metric("Sunrise", "N/A") st.metric("Sunset", "N/A") st.subheader(f"Current Weather in {city}") weather_description = weather_data['weather'][0]['description'].capitalize() st.write(f"**Description:** {weather_description}") weather_icon_code = weather_data['weather'][0]['icon'] weather_icon_url = f"http://openweathermap.org/img/w/{weather_icon_code}.png" st.image(weather_icon_url, width=100) lat = weather_data['coord']['lat'] lon = weather_data['coord']['lon'] map_data = pd.DataFrame({'lat': [lat], 'lon': [lon]}) st.map(map_data, zoom=10) if st.button("Refresh"): st.experimental_rerun() else: st.write("Please enter a valid city name.") else: st.write("Please enter a city name.")