CMU Coding Bootcamp
1import pandas as pd
2import requests
3from geopy.geocoders import Nominatim
4from geopy.location import Location
5import datetime
6import seaborn as sns
7import matplotlib.pyplot as plt
8
9def sunrise_time(location_name: str, date: str|None|tuple[str,str] = None) -> list[dict[str, str]]:
10 nominatim = Nominatim(user_agent="CMU_Bootcamp")
11 geo: Location | None = nominatim.geocode(location_name)
12 if not geo:
13 raise KeyError("Location not found")
14 params = {
15 "lng": geo.longitude,
16 "lat": geo.latitude
17 }
18
19 if isinstance(date, tuple):
20 params["date_start"] = date[0],
21 params["date_end"] = date[1]
22 else:
23 params["date"] = date if date else "today"
24
25 out = requests.get(
26 "https://api.sunrisesunset.io/json",
27 params
28 )
29 j = out.json()['results']
30 res = j if isinstance(j, list) else [j]
31 return [{
32 "sunrise": r["sunrise"],
33 "sunset": r["sunset"],
34 "date": r["date"]
35 } for r in res]
36
37def dayLength(sunrise: str, sunset: str) -> float:
38 sr = datetime.datetime.strptime(sunrise, "%I:%M:%S %p")
39 ss = datetime.datetime.strptime(sunset, "%I:%M:%S %p")
40 srhr = round(sr.hour + sr.minute/60, 1)
41 sshr = round(ss.hour + ss.minute/60, 1)
42 length = sshr - srhr
43 return round(length, 1)
44
45location = "5000 Forbes Ave, Pittsburgh"
46print("Running checks...")
47try:
48 compare_date = "2024-08-02"
49 a = sunrise_time("Juneau, Alaska", compare_date)
50 b = sunrise_time("Miami, Florida", compare_date)
51 print(f"Juneau, Alaska {a[0]["sunrise"]}\nMiami, Florida {b[0]["sunrise"]}")
52 df = pd.DataFrame(sunrise_time("Seattle, Washington", ("2023-01-01", "2023-12-31")))
53 print(f"Latest: {df["sunrise"].max()} | Earliest: {df["sunrise"].min()}")
54 df = df.assign(dayLengthInHours=df.apply(lambda row: dayLength(row["sunrise"], row["sunset"]), axis=1))
55 print(f"Longest: {df["dayLengthInHours"].max()} | Shortest: {df['dayLengthInHours'].min()}")
56 # ax = sns.lineplot(data=df["dayLengthInHours"])
57 # ax.set(xlabel="", ylabel="", xticklabels=[])
58 # plt.show()
59 df = df.assign(month=df.apply(lambda row: datetime.datetime.strptime(row["date"], "%Y-%m-%d").strftime("%B"), axis=1))
60 print(df)
61 avgs: dict[str, float] = {}
62 for month in df["month"].unique():
63 this_month = pd.DataFrame(df[df["month"] == month])
64 total = this_month["dayLengthInHours"].astype(float).sum()
65 avg = round(total / len(this_month), 1)
66 avgs[month] = avg
67 # ax = sns.barplot(data=avgs)
68 # ax.tick_params(axis="x", rotation=45)
69 # plt.show()
70 print("Passed!")
71except:
72 print("Failed :(")