我想让我的家庭自动化项目在日落时开灯。我用这个代码从我的位置获取日落:
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,所以我的问题是:
我想做的是:
Get the time now
Get sunset time
If time.now > sunset
switch light on
我有大约5个小时的时间来找到答案,否则我要等24个小时来测试:)
以下是您的完整代码:
您需要
time
模块和strptime
函数来解析值。我让你自己学习格式规范,网址如下: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior这个例子解析你的时间并输出它
相关问题 更多 >
编程相关推荐