[英]How do I add an hour to sunset time?
我已經運行了一個Python腳本,該腳本獲取日落時間,將其與現在的時間進行比較,並在以后的時間點亮。
在一天的特定時間之間,每15分鍾通過一次cron作業來運行此操作,這樣它就可以覆蓋全年。
但是,我想做的是,如果日落之后1小時以上,則停止照明。
為什么? 我剛偏頭痛時才晚上7.00左右上床睡覺。 日落時燈已經亮了。 我把它們關掉了。 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
刪除import timedelta
並致電
datetime.timedelta(hours=1)
代替。
您導入了一個名為“ timedelta”的模塊,並試圖調用該模塊,而不是該模塊的功能。 但是,除了datetime中的模塊,我找不到名為timedelta的模塊。
實際上,我需要的是:
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小時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.