-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfive_day_weather_forecast.py
130 lines (101 loc) · 4.18 KB
/
five_day_weather_forecast.py
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import requests
import calendar
from collections import defaultdict
api_key = "<your_api_key>"
api_call = "https://api.openweathermap.org/data/2.5/forecast?appid=" + api_key
invalid_input_message = "Sorry, I didn't get that."
print("Welcome to Jaimes Subroto's 5 day weather forecast application using the OpenWeatherMap Weather API!")
if api_key == "<your_api_key>":
print("Please provide your OpenWeatherMap API key.")
exit()
def print_goodbye_messages():
print("Thank you for using Jaimes Subroto's 5 day weather forecast application.")
print("Have a great day!")
def get_city_or_zip_code():
while True:
try:
print("\nThis application supports search by city(0) or by zip code(1).")
search = int(input("Please input 0 or 1: "))
except ValueError:
print(invalid_input_message)
else:
if search == 0:
city = input("Please input the city name: ")
if city.lower() == "sf":
city = "San Francisco, US"
return "&q=" + city
elif search == 1:
zip_code = input("Please input the zip code: ")
return "&zip=" + zip_code
else:
# Prints the invalid number (not 0 or 1)
print("{} is not a valid option.".format(search))
is_running = True
while is_running:
# Stores the Json response
response = requests.get(api_call + get_city_or_zip_code())
json_data = response.json()
if response.status_code == 401:
print("Got a 401 response.")
print(json_data["message"])
print_goodbye_messages()
exit()
location_data = {
"city": json_data["city"]["name"],
"country": json_data["city"]["country"]
}
print("\n{city}, {country}".format(**location_data))
grouped_data = defaultdict(list)
forecasted_days = set()
# Iterates through the array of dictionaries named list in json_data
for item in json_data["list"]:
# Time of the weather data received, partitioned into 3 hour blocks
time = item["dt_txt"]
# Split the time into date and hour [YYYY-MM-DD 06:00:00]
date, hour = time.split(' ')
# Splits the YYYY-MM-DD string into separate date variables
year, month, day = date.split('-')
# Store the date in MM/DD/YYYY format
date = f"{month}/{day}/{year}"
# Add the day to display the forecasted days at the end
forecasted_days.add(day)
# Grabs the first 2 characters from our HH:MM:SS string to get the hours
hour = int(hour[:2])
# Sets the AM (ante meridiem) or PM (post meridiem) period
meridiem = "AM" if hour < 12 else "PM"
if hour == 0:
hour = 12
elif hour > 12:
hour -= 12
# Formatted as [HH:MM AM/PM]
time = f"{hour}:00 {meridiem}"
# Temperature is measured in Kelvin
temperature = item["main"]["temp"]
# Weather conditions
description = item["weather"][0]["description"]
humidity = item["main"]["humidity"]
grouped_data[date].append((time, temperature, description, humidity))
for date in grouped_data:
print("\n" + date)
for time, temperature, description, humidity in grouped_data[date]:
print("\n" + time)
print("Weather condition: %s" % description)
print(f"Humidity: {humidity}%")
print("Celcius: {:.2f}".format(temperature - 273.15))
print("Fahrenheit: %.2f" % ((temperature - 273.15) * 9/5 + 32))
# Prints a calendar of the current month
calendar_month = calendar.month(int(year), int(month))
print('\n' + calendar_month)
print(f"Forecasted days: {', '.join(sorted(forecasted_days))}.")
# Asks the user if he/she wants to exit
while True:
continue_input = input("Anything else we can help you with? ")
if continue_input.lower() in {"yes", 'y'}:
print("Great!")
break
elif continue_input.lower() in {"no", 'n', "exit"}:
is_running = False
print_goodbye_messages()
break
else:
print(invalid_input_message)