In this post you will read his to retrieve your city's current information regarding the weather. In the process, you will be introduced to Python's datetime and json modules.
Weather data is freely available from OpenWeatherMap website.
JSON
JavaScript Object Notation (JSON) is a data structure that is independent of a programming language and computing platform. It is like a dictionary, map or associative array. The data structure is made up of key-value pairs that can be nested to any depth.
Here is a simple json structure, a person's name and contact number. You can read more about json here.
import json
# string in json format
json_str = '{"p1" : {"name": "Nandy", "number": 9879523517}, "p2" : {"name": "Shaw", "number": 8987675444}}'
# convert json structure to python dictionary
data = json.loads(json_str)
# check the data types
print(type(json_str))
print(type(data))
print(data["p2"]['name'])
Output Shaw
Handling date and time in Python
The datetime object in the module by the same name has all the components of date and time. We will see a small example. We will retrieve the datetime object corresponding to the current day. We will then extract the various components of date and time to display them.
from datetime import datetime
this_moment = datetime.now()
print(this_moment)
# datetime has several methods to access date and time components
day = this_moment.day
# instead of this_moment.month, get the month name using the strftime() method
month = this_moment.strftime('%B')
year = this_moment.year
print(f"Today's date is {day} {month}, {year}")
Output 2022-06-16 17:43:35.257272 Today's date is 16 June, 2022
The Program
In order to receive your weather data, you will need an access token before you can fetch the data from the URL. The access token is available when you register with your e-mail.
After registration, you will find your access token in your account details. Click on your account name to see a drop-down that contains the token. Copy that and keep it somewhere safe. You will need it whenever you want to download weather data.
The weather API returns response as a JSON object. We convert it to a Python's dict object to retrieve information.
Here's a typical response from the URL.
{
"coord": {
"lon": -122.08,
"lat": 37.39
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 282.55,
"feels_like": 281.86,
"temp_min": 280.37,
"temp_max": 284.26,
"pressure": 1023,
"humidity": 100
},
"visibility": 10000,
"wind": {
"speed": 1.5,
"deg": 350
},
"clouds": {
"all": 1
},
"dt": 1560350645,
"sys": {
"type": 1,
"id": 5122,
"message": 0.0139,
"country": "US",
"sunrise": 1560343627,
"sunset": 1560396563
},
"timezone": -25200,
"id": 420006353,
"name": "Mountain View",
"cod": 200
}
We read the data that we are interested in and ignore the rest.
# using openweathermap api
import sys
import requests, json
from datetime import datetime
# timezone definitions generated from the Olson database
import pytz
city_name = ''
def main():
city_name = input("Enter city: ")
print(f'City: {city_name}')
timestamp, current_temperature, feels_like, current_humidity, current_pressure, weather_description = getWeather(city_name)
date_time = datetime.fromtimestamp(timestamp)
print(f'Date: {date_time.day} {date_time.strftime("%B")}, {date_time.year}\nTime: {date_time.strftime("%I:%M %p")}\nTemperature: {current_temperature} C, feels like {feels_like} C\nHumidity: {current_humidity} %\nWeather: {weather_description}')
def getWeather(city_name):
api_key = "<access token>"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
# for the complete information available, see the json structure at https://openweathermap.org/current
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
# timestamp of client when the query was made
timestamp = x["dt"]
y = x["main"]
# convert to celsius
current_temperature = round(y["temp"] - 272.15)
feels_like = round(y["feels_like"] - 272.15)
# relative humidity in percentage
current_humidity = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
return (timestamp, current_temperature, feels_like, current_humidity, current_pressure, weather_description)
else:
print(" City Not Found. Exiting... ")
# Exit program
sys.exit(0)
if __name__ == "__main__":
main()
Exercise
- Try temperature display in Fahrenheit
- Display date and time in different formats