如何以JSON中的特定值为目标并比较tim

2024-10-05 14:21:25 发布

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

我想让我的家庭自动化项目在日落时开灯。我用这个代码从我的位置获取日落:

import requests
import json

url = "http://api.sunrise-sunset.org/json?lat=xx.xxxxxx&lng=-x.xxxxx"
response = requests.request("GET", url)
data=response.json()
print(json.dumps(data, indent=4, sort_keys=True))

这将返回:

{
    "results": {
        "astronomical_twilight_begin": "5:46:47 AM",
        "astronomical_twilight_end": "6:02:36 PM",
        "civil_twilight_begin": "7:08:37 AM",
        "civil_twilight_end": "4:40:45 PM",
        "day_length": "08:15:09",
        "nautical_twilight_begin": "6:26:43 AM",
        "nautical_twilight_end": "5:22:39 PM",
        "solar_noon": "11:54:41 AM",
        "sunrise": "7:47:07 AM",
        "sunset": "4:02:16 PM"
    },
    "status": "OK"
}

我才刚刚开始了解JSON,所以我的问题是:

  • 如何从上面提取日落时间
  • (在示例中)“4:02:16 PM”是时间吗?当我看到它的时候我就知道了但是 Python会知道这是一个实际时间吗,这样我就可以比较它了

我想做的是:

Get the time now
Get sunset time
If time.now > sunset
    switch light on

我有大约5个小时的时间来找到答案,否则我要等24个小时来测试:)


Tags: importjsonurltimeresponse时间amrequests
2条回答

以下是您的完整代码:

import requests
import datetime
import json

url = "https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400"
response = requests.request("GET", url)
data=response.json() #Getting JSON Data
sunset_time_str=data['results']['sunset'] #Getting the Sunset Time

current_date=datetime.date.today() #Getting Today Date
sunset_time=datetime.datetime.strptime(sunset_time_str,'%I:%M:%S %p') #Converting String time to datetime object so that we can compare it current time
sunset_date_time=datetime.datetime.combine(current_date,sunset_time.time()) #Combine today date and time to single object

current_date_time=datetime.datetime.now()

if current_date_time > sunset_date_time:
  print('Turn On light')
else:
  print('Dont Turn ON')

您需要time模块和strptime函数来解析值。我让你自己学习格式规范,网址如下: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

这个例子解析你的时间并输出它

import time
import datetime

data = {
    "results": {
        "astronomical_twilight_begin": "5:46:47 AM",
        "astronomical_twilight_end": "6:02:36 PM",
        "civil_twilight_begin": "7:08:37 AM",
        "civil_twilight_end": "4:40:45 PM",
        "day_length": "08:15:09",
        "nautical_twilight_begin": "6:26:43 AM",
        "nautical_twilight_end": "5:22:39 PM",
        "solar_noon": "11:54:41 AM",
        "sunrise": "7:47:07 AM",
        "sunset": "4:02:16 PM"
    },
    "status": "OK"
}

t = time.strptime(data['results']['sunset'], '%I:%M:%S %p')

sunset = datetime.datetime.fromtimestamp(time.mktime(t)).time()
now = datetime.datetime.now().time()

print('Now: {}, Sunset: {}'.format(now, sunset))
if now < sunset:
    print('Wait man...')
else:
    print('Turn it ON!')

相关问题 更多 >