Web抓取国家天气API在Python中获取正确格式时遇到困难

2024-09-28 23:07:48 发布

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

我正在尝试从该链接中获取数据”https://api.weather.gov/gridpoints/MFL/44,66“并将其转换为正确的格式。这就是挑战:

In this assignment, you should write a function (named gets_temperature_forecast()) that gets an address/city and returns temperatures forecasts (in Centigrade and Fahrenheit) from the National Weather Service. The function output should be like the following:

****Date: 2019-07-04 Time: 08:00:00 Temperature: 27.22 C (81.0 F)**** #with the little circle on top etc

在尝试格式化之前,它看起来是这样的

{'validTime': '2021-09-11T21:00:00+00:00/PT2H', 'value': 29.444444444444443}, {'validTime': '2021-09-11T23:00:00+00:00/PT1H', 'value': 28.333333333333332}, 

我在这个平台上研究了很多问题,但仍然有问题。我似乎无法正确格式化数据,当我试图提取时间时,我没有成功地将其转换为常规时间,加上我的最后一行代码无法工作。我想我可能需要使用datetime函数来删除日期,但是我无法转换它。对于摄氏度也是如此,以正确格式化C和F

任何帮助都将不胜感激

这是我的密码:

import datetime
import pandas as pd
import requests
import json

url = "https://api.weather.gov/gridpoints/MFL/44,66"

response = requests.get(url).json()
print(response) #checking to see i have the URL

data_cleaned = []

for time in response ['data']['values']: #here is where everything gets messed up 
    data_cleaned.append({
       'Date': time['validTime'],
       'Time': (time['T']),
       'Temperature': time['value'], (time['value']*1.8) + 32
        })
 

Tags: thehttpsimportapidatatimevalueresponse
1条回答
网友
1楼 · 发布于 2024-09-28 23:07:48

试试这个:

gets_temperature_forecast(address, city):

    url = 'https://api.weather.gov/gridpoints/MFL/44,66'
    response = requests.get(url).json()
    
    time = response['temperature']['values'][0]['validTime']
    temp = response['temperature']['values'][0]['value']
    
    print(f"Temperature: {temp}\nTime: {time}")

我希望这有助于你走上正确的道路,尽管你需要通过自己检查API文档来找出如何使用地址/城市获取这些统计数据。(我知道你需要在列表中添加dicts,但我认为我向你展示的示例有望帮助你自己解决其余的问题)

相关问题 更多 >