【发布时间】:2018-12-06 22:01:04
【问题描述】:
我有一个 Python 脚本正在运行,它可以获取日落时间,将其与现在的时间进行比较,如果晚了就打开灯。
这会在一天中的某些时间之间每 15 分钟通过一个 cron 作业运行一次,因此它应该涵盖全年。
但我想做的是阻止它在日落后 1 小时以上打开灯。
为什么?由于偏头痛,我刚在晚上 7 点左右上床睡觉。灯在日落时亮了。我把它们关掉了。 15 分钟后,我意识到我的家庭自动化计划存在严重缺陷,因为我被突然亮起的 2 盏灯粗暴地吵醒了 :)
这是我的代码的相关位:
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
【问题讨论】:
-
看起来您可能已经调用了您的模块之一
timedelta?你的进口是什么? -
是的,我已经安装了 timedelta 并导入了它。我不确定的是我的哪些变量是一个支持添加 1 小时概念的变量。他们是时间,还是我正在尝试为“苹果”增加 1 小时?
-
Timedelta 不是一个函数,它是一个模块。例如,该函数看起来像“timedelta.timedelta()”。