PearDrop
PearDrop

Reputation: 69

OpenWeatherMap API, How do I fetch the temp?

Using Openweather JSON API, I am fetching the data from cities. I can retrieve all the data,the data I am focused on is the temp, and dt_txt.

I have tried getting the temp by doing this but it doesn't work:

import requests

def getCity():
    allCityName = ["London"]
    for cityName in allCityName:
        url = "http://api.openweathermap.org/data/2.5/forecast?q="+ cityName +"&appid="
        response = requests.get(url)
        data = response.json()
        print(data["main"]["temp"]

I've tried many combinations but always seem to get an error or no result. Any help would be appreciated.

Upvotes: 1

Views: 451

Answers (1)

Jonathan Leon
Jonathan Leon

Reputation: 5648

maybe you don't realize this but there are more than 1 temp and dt_text returned for each city. So you can't just pull one out unless you know you want the first, last or somewhere in the middle. Or if you want them all you have to collect them in a list, for example

data = getCity()
for d in data['list']:
    print(d['main']['temp'])
    print(d['dt_txt'])

281.44
2020-12-15 06:00:00
281.33
2020-12-15 09:00:00
283.54
2020-12-15 12:00:00
283.19
2020-12-15 15:00:00
281.88
2020-12-15 18:00:00
281.4
2020-12-15 21:00:00
281.17
2020-12-16 00:00:00
281.59
2020-12-16 03:00:00
281.75
2020-12-16 06:00:00
281.95
2020-12-16 09:00:00
283.61
2020-12-16 12:00:00
282.86
2020-12-16 15:00:00
282.99
2020-12-16 18:00:00
283.17
2020-12-16 21:00:00
281.61
2020-12-17 00:00:00
281.19
2020-12-17 03:00:00
281.27
2020-12-17 06:00:00
280.81
2020-12-17 09:00:00
282.71
2020-12-17 12:00:00
282.64
2020-12-17 15:00:00
281.16
2020-12-17 18:00:00
282.16
2020-12-17 21:00:00
282.52
2020-12-18 00:00:00
283.4
2020-12-18 03:00:00
284.03
2020-12-18 06:00:00
283.86
2020-12-18 09:00:00
284.4
2020-12-18 12:00:00
284.19
2020-12-18 15:00:00
283.87
2020-12-18 18:00:00
284.21
2020-12-18 21:00:00
284.34
2020-12-19 00:00:00
284.53
2020-12-19 03:00:00
284.44
2020-12-19 06:00:00
283.48
2020-12-19 09:00:00
284.81
2020-12-19 12:00:00
284.55
2020-12-19 15:00:00
283.7
2020-12-19 18:00:00
283.33
2020-12-19 21:00:00
282.42
2020-12-20 00:00:00
281.76
2020-12-20 03:00:00

temps = [d['main']['temp'] for d in data['list']]

In [59]: print(temps)
[281.44, 281.33, 283.54, 283.19, 281.88, 281.4, 281.17, 281.59, 281.75, 281.95, 283.61, 282.86, 282.99, 283.17, 281.61, 281.19, 281.27, 280.81, 282.71, 282.64, 281.16, 282.16, 282.52, 283.4, 284.03, 283.86, 284.4, 284.19, 283.87, 284.21, 284.34, 284.53, 284.44, 283.48, 284.81, 284.55, 283.7, 283.33, 282.42, 281.76]

Upvotes: 1

Related Questions