我根據if語句中的移動和一天中的時間做了一些代碼來打開燈光。如果(本地)時間在日出與預設時間或日落之間以及預設時間之間,則if語句爲真,並且將跟隨移動檢測語句。如何在if語句中使用localtime(HH:MM) - python
目前時間僅以小時爲單位以整數表示。我怎樣才能讓我的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'解碼,而不是字符串索引。 – Daniel
你不需要定義變量。 – Daniel
'datetime.time'實現了比較運算符,即 't1 = dt.time(6,45,0)' 't2 = dt.time(6,40,0)' 't1> t2' returns' True'加上'datetime.datetime.strptime'方法也可以很容易地將字符串解析爲'time'和'date'對象 – ChE