weather.py 文件源码

python
阅读 25 收藏 0 点赞 0 评论 0

项目:discordtest 作者: asdfblarg 项目源码 文件源码
def call_weather_api(location):
    """ Call API """

    request = urllib.request.urlopen(url % location)

    payload = json.loads(request.read())

    if 'cod' in payload and payload['cod'] == '200':
        if 'list' in payload:
            data = payload['list'][0]
            location = data['name']

            if 'dt' in data:
                measured = datetime.utcfromtimestamp(data['dt'])
                if datetime.utcnow() - timedelta(minutes=threshold) > measured:
                    text = '%s (%s UTC): ' % (location, measured.strftime('%Y-%m-%d %H:%M'))
                else:
                    text = '%s: ' % location
            else:
                text = '%s: ' % location

            main = data['main']
            if 'temp' in main:
                temperature = main['temp'] - 273.15  # temperature converted from kelvins to celcius and rounded
                text += 'Temperature: %.1fc' % temperature
            else:
                temperature = None
            if 'wind' in data and 'speed' in data['wind']:
                wind = data['wind']['speed']  # Wind speed in mps (m/s)
            else:
                wind = None
            if temperature and wind:
                feels_like = 13.12 + 0.6215 * temperature - 11.37 * (wind * 3.6) ** 0.16 + 0.3965 * temperature * (wind * 3.6) ** 0.16
                text += ', Feels like: %.1fc' % feels_like
            if wind:
                text += ', Wind: %.1f m/s' % wind
            if 'humidity' in main:
                humidity = main['humidity']  # Humidity in %
                text += ', Humidity: %d%%' % humidity
            if 'pressure' in main:
                pressure = main['pressure']  # Atmospheric pressure in hPa
                text += ', Pressure: %d hPa' % pressure
            if 'clouds' in data and 'all' in data['clouds']:
                cloudiness = data['clouds']['all']  # Cloudiness in %
                text += ', Cloudiness: %d%%' % cloudiness

            if temperature:
                print(text.encode('utf-8'))
            else:
                print('Error: No data.')
    else:
        print('Error: Location %s not found.' % location)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号