【发布时间】:2016-12-24 16:37:10
【问题描述】:
我在 if 语句中编写了一些代码来根据运动和一天中的时间打开灯。如果(本地)时间在日出和预设时间或日落和预设时间之间,则 if 语句为真,运动检测语句将跟随。
目前时间仅以小时为整数。我怎样才能让我的 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 新手,但不是编码新手。
您好, 泰斯
【问题讨论】:
-
你得到 json 响应,所以使用
json.loads解码而不是字符串索引。 -
你不需要定义变量。
-
datetime.time实现了比较运算符,即t1 = dt.time(6,45,0)t2 = dt.time(6,40,0)t1 > t2返回True加上它还具有datetime.datetime.strptime方法可以轻松地将字符串解析为time和date对象
标签: python python-2.7 if-statement localtime