File size: 3,369 Bytes
2ac2b9f
a0cb463
b6b9e6b
a0cb463
 
2ac2b9f
 
a0cb463
 
 
2ac2b9f
c2e5a3e
a0cb463
 
 
2ac2b9f
a0cb463
 
2ac2b9f
a0cb463
 
 
 
 
 
 
2ac2b9f
 
 
 
 
 
 
a0cb463
 
 
2ac2b9f
a0cb463
 
 
 
 
2ac2b9f
a0cb463
 
 
 
 
2ac2b9f
a0cb463
 
2ac2b9f
a0cb463
 
 
 
 
 
2ac2b9f
 
b6b9e6b
a0cb463
 
 
 
 
 
 
 
 
 
 
 
 
 
2ac2b9f
a0cb463
 
 
 
2ac2b9f
a0cb463
 
2ac2b9f
 
 
 
a0cb463
 
 
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# 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.")