我根据if语句中的移动和一天中的时间编写了一些代码来打开灯。如果(本地)时间在日出时间和预设时间之间,或者日落时间和预设时间之间,则if语句为true,则运动检测语句将跟随。
目前,时间仅以小时为单位显示为整数。我如何使我的if语句与小时和分钟一起工作(认为这将是一个字符串)。因此,该语句将适用于6:45而不是7。
这是我的代码。
import RPi.GPIO as GPIO
import time
import urllib2
from datetime import datetime
from business_calendar import Calendar, MO, TU, WE, TH, FR
from pytz import timezone
#uur
fmh = "%H"
fmt = "$H:%M"
#Def. var.
x=0
now_utc = 0
now_amsterdam = 0
print "Here we go! Press CTRL+C to exit"
try:
while x < 1:
count = 0
date = datetime.today()
#werkdag def.
cal = Calendar(workdays=[MO,TU,WE,TH,FR])
busday = cal.isbusday(date)
# dT AMS-UTC
now_utc = datetime.now(timezone('UTC'))
now_amsterdam = now_utc.astimezone(timezone('Europe/Amsterdam'))
UTC = int(now_utc.strftime(fmh))
AMS = int(now_amsterdam.strftime(fmh))
dT = AMS - UTC
# Zonsopgang/Ondegang
request = 'http://api.sunrise-sunset.org/json?lat=51.9913XXX&lng=4.4733XXX&formatted=0'
response = urllib2.urlopen(request)
timestring = response.read()
utcsunrise = timestring[35:39] #Will be 35:39 for HH:MM and cant be a string then
utcsunset = timestring[71:73] #Will be 71:79 for HH:MM
amssunrise = int(utcsunrise) + dT #Wont work with a string
amssunset = int(utcsunset) + dT
if amssunrise < 8 #Will be 7:30
amssunrise = 8 #Will be 7:30
if amssunset < 21 #Will be 21:30
amssunset = 21 #Will be 21:30
#uur
uur = date.hour #Must be HH:MM instead of only hours
if busday == True and ((uur >= 7 and uur <= amssunrise) or (uur >= amssunset and uur <= 23)):
# rest of the statements
# end statement
except KeyboardInterrupt:
GPIO.cleanup()
我想听听您的想法。请注意,我是python的新手,但不是编码人员。
问候,Thijs
使用datetime
-objects进行所有计算:
import RPi.GPIO as GPIO
import time
import urllib2
import json
from datetime import datetime
from business_calendar import Calendar, MO, TU, WE, TH, FR
from pytz import timezone, utc
local_timezone = timezone('Europe/Amsterdam')
print "Here we go! Press CTRL+C to exit"
try:
while True:
#werkdag def.
cal = Calendar(workdays=[MO,TU,WE,TH,FR])
busday = cal.isbusday(date)
now = datetime.now(local_timezone)
work_start = now.replace(hour=7, minute=0, second=0, microsecond=0)
work_end = now.replace(hour=23, minute=0, second=0, microsecond=0)
# Zonsopgang/Ondegang
request = 'http://api.sunrise-sunset.org/json?lat=51.9913XXX&lng=4.4733XXX&formatted=0'
response = urllib2.urlopen(request)
timestring = json.loads(response.read())
sunset = datetime.strptime(timestring['results']['sunset'],'%Y-%m-%dT%H:%M:%S+00:00')
sunset = utc.localize(sunset).astimezone(local_timezone)
sunrise = datetime.strptime(timestring['results']['sunrise'],'%Y-%m-%dT%H:%M:%S+00:00')
sunrise = utc.localize(sunset).astimezone(local_timezone)
if busday and (work_start <= now <= sunrise or sunset <= now <= work_end):
# rest of the statements
# end statement
except KeyboardInterrupt:
GPIO.cleanup()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句