11import requests
22from datetime import datetime
3+ from Util_Functions import (
4+ wind_degree_to_direction ,
5+ unix_timestamp_to_localtime ,
6+ convert_temperature ,
7+ )
38
49
5- # Function to fetch weather data from OpenWeatherMap API
610def 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+ """
721 try :
822 # Constructing the API link with the provided API key and location
923 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):
2337 return None
2438
2539
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+
2849 try :
2950 # Opening the file "weatherinfo.txt" in write mode
3051 with open ("weatherinfo.txt" , "w+" ) as f :
3152 # Getting the current date and time
3253 date_time = datetime .now ().strftime ("%d %b %Y | %I:%M:%S %p" )
3354
3455 # 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+ )
3871
3972 # Writing temperature information to the file
4073 if "main" in weather_data and "temp" in weather_data ["main" ]:
4174 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
4478 )
79+ + "\n "
4580 )
4681
4782 # Writing weather description information to the file
@@ -68,6 +103,42 @@ def write_to_file(location, weather_data):
68103 )
69104 )
70105
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+
71142 # Printing confirmation message after writing to file
72143 print ("Weather information written to weatherinfo.txt" )
73144
@@ -76,36 +147,76 @@ def write_to_file(location, weather_data):
76147 print ("Error writing to file:" , e )
77148
78149
79- # Main function
80150def main ():
151+ """
152+ Main function.
153+ """
81154 # Printing welcome messages and instructions
82155 print ("Welcome to the Weather Information App!" )
83156 print ("You need an API key to access weather data from OpenWeatherMap." )
84157 print (
85158 "You can obtain your API key by signing up at https://home.openweathermap.org/users/sign_up"
86159 )
87160
88- # Prompting the user to input API key and city name
161+ # Prompting the user to input API key, city name, and temperature unit
89162 api_key = input ("Please enter your OpenWeatherMap API key: " )
90163 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
91171
92172 # Fetching weather data using the provided API key and location
93173 weather_data = fetch_weather (api_key , location )
94174
95175 # Checking if weather data was successfully fetched
96176 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+
97187 # Writing weather information to file
98- write_to_file (location , weather_data )
188+ write_to_file (weather_data , temperature_unit )
99189
100190 # Printing weather information to console
101191 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 )
105200 )
106201 print ("Current weather desc : " + weather_data ["weather" ][0 ]["description" ])
107202 print ("Current Humidity :" , weather_data ["main" ]["humidity" ], "%" )
108203 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+ )
109220 else :
110221 # Printing error message if weather data fetching fails
111222 print ("Failed to fetch weather data. Please check your input and try again." )
0 commit comments