我已经运行了一个Python脚本,该脚本获取日落时间,将它与现在的时间进行比较,如果稍后打开,则打开灯。
在一天中的特定时间,每15分钟通过cron作业运行一次,这样就可以覆盖全年。
但我想做的是,如果它比日落后1小时还多的话,就不要把灯打开。
为什么?我刚在晚上7点左右上床睡觉,因为我偏头痛。日落时灯光亮了。我把它们关掉了。15分钟后,我意识到我的家庭自动化计划有很大的缺陷,因为我突然被两盏灯突然亮了起来。)
这是我代码的相关部分:
url = "https://api.sunrise-sunset.org/json?lat=51.218675&lng=-1.467375"
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()
stop_time = ??????????????????? + timedelta(hours=1)
print (stop_time)
if current_date_time > sunset_date_time:
#turn the light on这就是“?”的意思。我一直在纠结。我尝试过sunset_date_time和其他一些东西,但是我只得到了一个错误(例如):
Traceback (most recent call last):
File "/home/pi/libcoap/light.py", line 41, in <module>
stop_time = sunset_date_time + timedelta(hours=1)
TypeError: 'module' object is not callable有人能给我一条救生索吗。我已经搜索过了,但是所有的例子都提到现在在时间上增加一个小时(或其他什么),而不是不同的时间。
编辑:添加导入
from pytradfri import Gateway
from pytradfri.api.libcoap_api import APIFactory
from pytradfri.util import load_json, save_json
from time import sleep
import requests
import datetime
import time
import json
import timedelta发布于 2018-12-08 00:45:43
实际上,我需要的是:
from pytradfri import Gateway
from pytradfri.api.libcoap_api import APIFactory
from pytradfri.util import load_json, save_json
from time import sleep
import requests
import datetime
import time
import json
from datetime import timedelta #This is the line I was missing
url = "https://api.sunrise-sunset.org/json?lat=51.218675&lng=-1.467375"
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 compar$
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()
stop_time = sunset_date_time + timedelta(hours=1) #This gives me the time of sunset + 1 hour
print (stop_time)这将打印日期和日落时间+1小时。
发布于 2018-12-07 09:04:01
删除import timedelta并调用
datetime.timedelta(hours=1)而不是。
您导入了一个名为"timedelta“的模块,并试图调用该模块,而不是模块的一个函数。不过,除了约会时间里的那个之外,我找不到一个名为timedelta的模块。
https://stackoverflow.com/questions/53660340
复制相似问题