如何从openweathermap.org获取每小时天气?

问题描述

现在,我只能请求当前时间的天气。但是,我想请求当前天气以及此后的每小时天气。

This is sort of what i want

要查找当前的天气,我使用了https://openweathermap.org/current,但是我试图使用https://openweathermap.org/api/hourly-forecast获取每小时数据,但是当我查看示例.json时,我不知道如何更改是时候获取当时的天气了。

这是我如何获取当前天气数据的示例:

combined = city + ',' + country
weatherkey = '****'
url = 'https://api.openweathermap.org/data/2.5/weather'
params = {'APPID' : weatherkey,'q' : combined,'units' : 'metric'}
response = requests.get(url,params = params)
weather = response.json()

desc = string.capwords(str(weather['weather'][0]['description']))
temp = str(round(weather['main']['temp'],1)) + '°C'

print(desc)
print(temp)

谢谢

解决方法

看起来像https://openweathermap.org/api/hourly-forecast会给您一个预测列表。

查看list.dt值,它是“预测数据时间,Unix,UTC”。

遍历列表并找到与您感兴趣的时间(尽可能接近)匹配的时间值。您必须使用API​​提供的值,猜测哪个值不是一个好主意。预测已存在,相反,您必须检查每个list.dt值,直到找到所需的值为止(如果您正在寻找特定的预测)。

例如,假设您要查找2020年8月5日(星期三)14:00:00(UTC)的预测,即Unix时间为1596636000。

(请原谅pythonesque代码,将其视为伪代码)

requested_time = 1596636000
for forecast in api_response["list"]:
   if forecast.dt => requested_time:
      print forecast
      break
,

您需要使用 onecall API:

https://api.openweathermap.org/data/2.5/onecall

这使您可以根据分钟、每小时、每天和警报获取当前天气和预报。您可以使用 exclude 参数定制返回的内容:

&exclude=daily,minutely,current,alerts

示例:

https://api.openweathermap.org/data/2.5/onecall?lat=-41.211128&lon=174.908081&exclude=daily,alerts&units=metric&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

其中 xxxx 是您的 API 密钥。从那里,您需要参考响应格式的文档并解析 json。