1
1
import requests
2
2
from datetime import datetime
3
+ from Util_Functions import (
4
+ wind_degree_to_direction ,
5
+ unix_timestamp_to_localtime ,
6
+ convert_temperature ,
7
+ )
3
8
4
9
5
- # Function to fetch weather data from OpenWeatherMap API
6
10
def fetch_weather (api_key , location ):
11
+ """
12
+ Function to fetch weather data from OpenWeatherMap API.
13
+
14
+ Parameters:
15
+ api_key (str): API key.
16
+ location (str): City name.
17
+
18
+ Returns:
19
+ str: The JSON response string.
20
+ """
7
21
try :
8
22
# Constructing the API link with the provided API key and location
9
23
complete_api_link = f"https://api.openweathermap.org/data/2.5/weather?q={ location } &appid={ api_key } "
@@ -23,25 +37,46 @@ def fetch_weather(api_key, location):
23
37
return None
24
38
25
39
26
- # Function to write weather information to a text file
27
- def write_to_file (location , weather_data ):
40
+ def write_to_file (weather_data , temperature_unit ):
41
+ """
42
+ Function to write weather information to a text file.
43
+
44
+ Parameters:
45
+ weather_data (str): The JSON API response string.
46
+ temperature_unit (str): 'C' for Celsius, 'F' for Fahrenheit.
47
+ """
48
+
28
49
try :
29
50
# Opening the file "weatherinfo.txt" in write mode
30
51
with open ("weatherinfo.txt" , "w+" ) as f :
31
52
# Getting the current date and time
32
53
date_time = datetime .now ().strftime ("%d %b %Y | %I:%M:%S %p" )
33
54
34
55
# Writing header information to the file
35
- f .write ("-------------------------------------------------------------\n " )
36
- f .write (f"Weather Stats for - { location .upper ()} || { date_time } \n " )
37
- f .write ("-------------------------------------------------------------\n " )
56
+ if (
57
+ "name" in weather_data
58
+ and "sys" in weather_data
59
+ and "country" in weather_data ["sys" ]
60
+ ):
61
+ f .write (
62
+ "-------------------------------------------------------------\n "
63
+ )
64
+ f .write (
65
+ f"Weather Stats for - { weather_data ['name' ]} | { weather_data ['sys' ]['country' ]} "
66
+ f"| { date_time } \n "
67
+ )
68
+ f .write (
69
+ "-------------------------------------------------------------\n "
70
+ )
38
71
39
72
# Writing temperature information to the file
40
73
if "main" in weather_data and "temp" in weather_data ["main" ]:
41
74
f .write (
42
- "\t Current temperature is : {:.2f} °C\n " .format (
43
- weather_data ["main" ]["temp" ] - 273.15
75
+ "\t Current temperature is : "
76
+ + convert_temperature (
77
+ weather_data ["main" ]["temp" ], temperature_unit
44
78
)
79
+ + "\n "
45
80
)
46
81
47
82
# Writing weather description information to the file
@@ -68,6 +103,42 @@ def write_to_file(location, weather_data):
68
103
)
69
104
)
70
105
106
+ # Writing wind direction information to the file
107
+ if "wind" in weather_data and "deg" in weather_data ["wind" ]:
108
+ f .write (
109
+ "\t Current wind direction : "
110
+ + wind_degree_to_direction (weather_data ["wind" ]["deg" ])
111
+ + " \n "
112
+ )
113
+
114
+ # Writing sunrise local time to the file
115
+ if (
116
+ "sys" in weather_data
117
+ and "sunrise" in weather_data ["sys" ]
118
+ and "timezone" in weather_data
119
+ ):
120
+ f .write (
121
+ "\t Today's sunrise time : "
122
+ + unix_timestamp_to_localtime (
123
+ weather_data ["sys" ]["sunrise" ], weather_data ["timezone" ]
124
+ )
125
+ + " \n "
126
+ )
127
+
128
+ # Writing sunset local time to the file
129
+ if (
130
+ "sys" in weather_data
131
+ and "sunset" in weather_data ["sys" ]
132
+ and "timezone" in weather_data
133
+ ):
134
+ f .write (
135
+ "\t Today's sunset time : "
136
+ + unix_timestamp_to_localtime (
137
+ weather_data ["sys" ]["sunset" ], weather_data ["timezone" ]
138
+ )
139
+ + " \n "
140
+ )
141
+
71
142
# Printing confirmation message after writing to file
72
143
print ("Weather information written to weatherinfo.txt" )
73
144
@@ -76,36 +147,76 @@ def write_to_file(location, weather_data):
76
147
print ("Error writing to file:" , e )
77
148
78
149
79
- # Main function
80
150
def main ():
151
+ """
152
+ Main function.
153
+ """
81
154
# Printing welcome messages and instructions
82
155
print ("Welcome to the Weather Information App!" )
83
156
print ("You need an API key to access weather data from OpenWeatherMap." )
84
157
print (
85
158
"You can obtain your API key by signing up at https://home.openweathermap.org/users/sign_up"
86
159
)
87
160
88
- # Prompting the user to input API key and city name
161
+ # Prompting the user to input API key, city name, and temperature unit
89
162
api_key = input ("Please enter your OpenWeatherMap API key: " )
90
163
location = input ("Enter the city name: " )
164
+ temperature_unit = input (
165
+ "Enter the temperature unit. 'C' for Celsius and 'F' for Fahrenheit: "
166
+ )
167
+
168
+ if not (temperature_unit .upper () == "C" or temperature_unit .upper () == "F" ):
169
+ print ("Temperature unit must either be 'C' or be 'F'." )
170
+ return
91
171
92
172
# Fetching weather data using the provided API key and location
93
173
weather_data = fetch_weather (api_key , location )
94
174
95
175
# Checking if weather data was successfully fetched
96
176
if weather_data :
177
+ # Checking if the API key is invalid
178
+ if weather_data ["cod" ] == "401" :
179
+ print ("Invalid API key." )
180
+ return
181
+
182
+ # Checking if the city is not found
183
+ if weather_data ["cod" ] == "404" :
184
+ print ("City not found." )
185
+ return
186
+
97
187
# Writing weather information to file
98
- write_to_file (location , weather_data )
188
+ write_to_file (weather_data , temperature_unit )
99
189
100
190
# Printing weather information to console
101
191
print (
102
- "Current temperature is: {:.2f} °C" .format (
103
- weather_data ["main" ]["temp" ] - 273.15
104
- )
192
+ "Current City : "
193
+ + weather_data ["name" ]
194
+ + ", "
195
+ + weather_data ["sys" ]["country" ]
196
+ )
197
+ print (
198
+ "Current temperature is: "
199
+ + convert_temperature (weather_data ["main" ]["temp" ], temperature_unit )
105
200
)
106
201
print ("Current weather desc : " + weather_data ["weather" ][0 ]["description" ])
107
202
print ("Current Humidity :" , weather_data ["main" ]["humidity" ], "%" )
108
203
print ("Current wind speed :" , weather_data ["wind" ]["speed" ], "kmph" )
204
+ print (
205
+ "Current wind direction:" ,
206
+ wind_degree_to_direction (weather_data ["wind" ]["deg" ]),
207
+ )
208
+ print (
209
+ "Today's sunrise time :" ,
210
+ unix_timestamp_to_localtime (
211
+ weather_data ["sys" ]["sunrise" ], weather_data ["timezone" ]
212
+ ),
213
+ )
214
+ print (
215
+ "Today's sunset time :" ,
216
+ unix_timestamp_to_localtime (
217
+ weather_data ["sys" ]["sunset" ], weather_data ["timezone" ]
218
+ ),
219
+ )
109
220
else :
110
221
# Printing error message if weather data fetching fails
111
222
print ("Failed to fetch weather data. Please check your input and try again." )
0 commit comments