OpenWeatheMapAPI表示温度大约为282

2024-05-11 18:43:42 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我用python编写了一个程序,告诉你天气情况,我正在使用OpenWeatherMapAPI来做到这一点

当我得到信息的时候,温度真的很低吗?我认为这是一个API,但我对此表示怀疑

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"base":"stations","main":{"temp":282.48,"feels_like":277.86,"temp_min":282.04,"temp_max":283.15,"pressure":981,"humidity":87},"visibility":10000,"wind":{"speed":5.7,"deg":240},"rain":{"1h":1.15},"clouds":{"all":100},"dt":1601797507,"sys":{"type":1,"id":1414,"country":"GB","sunrise":1601791589,"sunset":1601832694},"timezone":3600,"id":2643743,"name":"London","cod":200}

我想要摄氏温度,但我不知道怎么计算

这是我的密码:

weathercity = input("What city are you in? ")
weather = requests.get('http://api.openweathermap.org/data/2.5/weather?q='+weathercity+'&appid=...')
url = ('http://api.openweathermap.org/data/2.5/weather?q='+weathercity+'&appid=...')



data = weather.json()

temp = data['main']['temp']
description = data['weather'][0]['description']
weatherprint ="In {}, it is currently {}° with {}."
spinner = spinning_cursor()
for _ in range(25):
    sys.stdout.write(next(spinner))
    sys.stdout.flush()
    time.sleep(0.1)
    sys.stdout.write('\b')
print(weatherprint.format(weathercity, temp, description))

Tags: inorgapiidhttpdatamainstdout
2条回答
import requests
import time
import sys

weathercity = input("What city are you in? ")
weather = requests.get('http://api.openweathermap.org/data/2.5/weather?q='+weathercity+'&appid=886705b4c1182eb1c69f28eb8c520e20')
url = ('http://api.openweathermap.org/data/2.5/weather?q='+weathercity+'&appid=886705b4c1182eb1c69f28eb8c520e20')




def spinning_cursor():
    while True:
        for cursor in '|/-\\':
            yield cursor


data = weather.json()

temp = data['main']['temp']
description = data['weather'][0]['description']
weatherprint ="In {}, it is currently {}°C with {}."
spinner = spinning_cursor()
for _ in range(25):
    sys.stdout.write(next(spinner))
    sys.stdout.flush()
    time.sleep(0.1)
    sys.stdout.write('\b')

convert = int(temp - 273.15)
print(weatherprint.format(weathercity, convert, description))

正如documentation所述,默认温度单位为Kelvin。要获取celsius unit,请使用units=metric

另外,为了使其正确,我建议使用params参数传递URL参数

APP_ID = "..."
url = 'http://api.openweathermap.org/data/2.5/weather'
weather = requests.get(url, params={'units': 'metric',
                                    'appid': APP_ID,
                                    'q': weathercity})

相关问题 更多 >