1

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

这就是我想要的

像这样

要查找当前天气,我使用了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)

谢谢

4

2 回答 2

1

您需要使用 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,minutely,current,alerts&units=metric&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

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

于 2021-02-15T22:19:33.817 回答
0

看起来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
于 2020-08-27T08:37:35.680 回答