如何定位JSON中的特定值并比较时间

时间:2018-11-30 11:09:57

标签: python json time

我正试图让我的家庭自动化项目在日落时打开灯。我正在使用此代码从我的位置获取日落:

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”吗?我知道是当我看着它,但是 Python会知道这是一个实际时间,以便我可以进行比较吗?

我想做的是:

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

我有大约5个小时的时间来找到答案,否则我将不得不等待24个小时来进行测试:)

2 个答案:

答案 0 :(得分:1)

您需要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!')

答案 1 :(得分:1)

这是您的完整代码:

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')