import pandas as pd import requests from geopy.geocoders import Nominatim from geopy.location import Location import datetime import seaborn as sns import matplotlib.pyplot as plt def sunrise_time(location_name: str, date: str|None|tuple[str,str] = None) -> list[dict[str, str]]: nominatim = Nominatim(user_agent="CMU_Bootcamp") geo: Location | None = nominatim.geocode(location_name) if not geo: raise KeyError("Location not found") params = { "lng": geo.longitude, "lat": geo.latitude } if isinstance(date, tuple): params["date_start"] = date[0], params["date_end"] = date[1] else: params["date"] = date if date else "today" out = requests.get( "https://api.sunrisesunset.io/json", params ) j = out.json()['results'] res = j if isinstance(j, list) else [j] return [{ "sunrise": r["sunrise"], "sunset": r["sunset"], "date": r["date"] } for r in res] def dayLength(sunrise: str, sunset: str) -> float: sr = datetime.datetime.strptime(sunrise, "%I:%M:%S %p") ss = datetime.datetime.strptime(sunset, "%I:%M:%S %p") srhr = round(sr.hour + sr.minute/60, 1) sshr = round(ss.hour + ss.minute/60, 1) length = sshr - srhr return round(length, 1) location = "5000 Forbes Ave, Pittsburgh" print("Running checks...") try: compare_date = "2024-08-02" a = sunrise_time("Juneau, Alaska", compare_date) b = sunrise_time("Miami, Florida", compare_date) print(f"Juneau, Alaska {a[0]["sunrise"]}\nMiami, Florida {b[0]["sunrise"]}") df = pd.DataFrame(sunrise_time("Seattle, Washington", ("2023-01-01", "2023-12-31"))) print(f"Latest: {df["sunrise"].max()} | Earliest: {df["sunrise"].min()}") df = df.assign(dayLengthInHours=df.apply(lambda row: dayLength(row["sunrise"], row["sunset"]), axis=1)) print(f"Longest: {df["dayLengthInHours"].max()} | Shortest: {df['dayLengthInHours'].min()}") # ax = sns.lineplot(data=df["dayLengthInHours"]) # ax.set(xlabel="", ylabel="", xticklabels=[]) # plt.show() df = df.assign(month=df.apply(lambda row: datetime.datetime.strptime(row["date"], "%Y-%m-%d").strftime("%B"), axis=1)) print(df) avgs: dict[str, float] = {} for month in df["month"].unique(): this_month = pd.DataFrame(df[df["month"] == month]) total = this_month["dayLengthInHours"].astype(float).sum() avg = round(total / len(this_month), 1) avgs[month] = avg # ax = sns.barplot(data=avgs) # ax.tick_params(axis="x", rotation=45) # plt.show() print("Passed!") except: print("Failed :(")