2016-08-17 50 views
0

我根據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,但不是編碼。

問候, 泰斯

+0

你得到JSON響應,所以用'json.loads'解碼,而不是字符串索引。 – Daniel

+0

你不需要定義變量。 – Daniel

+0

'datetime.time'實現了比較運算符,即 't1 = dt.time(6,45,0)' 't2 = dt.time(6,40,0)' 't1> t2' returns' True'加上'datetime.datetime.strptime'方法也可以很容易地將字符串解析爲'time'和'date'對象 – ChE

回答

1

是否所有的計算與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() 
+0

謝謝你的工作很好!我只需要將utc定義爲utc..localize trough utc = timezone(ÚTC')並刪除datetime.datetime定義的一個datetime。 – Thijs

0

我不再使用內置datetime LIB它吮吸。看看arrowhttp://crsmithdev.com/arrow/

只是一個提示。

另外看看使用requests它實際上做python中的東西的方式。

我已經儘可能地重寫了您的應用程序,並提供了下面的鏈接。我不太確定你在哪裏試圖儘可能複製它,但是。我希望這有幫助。

http://hastebin.com/elomonacod.py

import arrow 
import requests 
import sys 
from business_calendar import Calendar, MO, TU, WE, TH, FR 

#uur 
fmh = "%H" 
fmt = "$H:%M" 

#Def. var. 
now_utc = 0 
now_amsterdam = 0 
some_condition = False 


def main(): 
    print "Here we go! Press CTRL+C to exit" 
    global now_amsterdam 
    global now_utc 
    global some_condition 
    while True: 
     count = 0 
     date = arrow.now() 

     # werkdag def. 
     cal = Calendar(workdays=[MO, TU, WE, TH, FR]) 
     busday = cal.isbusday(date) 

     # dT AMS-UTC 
     now_utc = arrow.utcnow() 
     now_amsterdam = now_utc.to('Europe/Amsterdam') 
     print now_utc, now_amsterdam 
     time_diff = now_amsterdam - now_utc 

     r = requests.get('http://api.sunrise-sunset.org/json?lat=51.9913XXX&lng=4.4733XXX&formatted=0') 
     if r.status_code != 200: 
      print('Server could not be reached: {}'.format(r.status_code)) 
      sys.exit() 

     ''' Data structure 
     { 
      "results": { 
       "sunrise": "2016-08-17T04:31:10+00:00", 
       "sunset": "2016-08-17T19:00:46+00:00", 
       "solar_noon": "2016-08-17T11:45:58+00:00", 
       "day_length": 52176, 
       "civil_twilight_begin": "2016-08-17T03:53:46+00:00", 
       "civil_twilight_end": "2016-08-17T19:38:10+00:00", 
       "nautical_twilight_begin": "2016-08-17T03:06:02+00:00", 
       "nautical_twilight_end": "2016-08-17T20:25:54+00:00", 
       "astronomical_twilight_begin": "2016-08-17T02:09:10+00:00", 
       "astronomical_twilight_end": "2016-08-17T21:22:46+00:00" 
      }, 
      "status": "OK" 
     } 
     ''' 

     data = r.json()['results'] 
     utc_sunrise = arrow.get(data['sunrise']) 
     utc_sunset = arrow.get(data['sunset']) 
     ams_sunrise = utc_sunrise + time_diff 
     ams_sunset = utc_sunset + time_diff 
     # Zonsopgang/Ondegang 
     if ams_sunrise < arrow.get('{} 07:30:00'.format(now_amsterdam.format('YYYY-MM-DD'))): 
      pass 

     if ams_sunset < arrow.get('{} 21:30:00'.format(now_amsterdam.format('YYYY-MM-DD'))): 
      pass 

     if busday: 
      pass 

     if some_condition: 
      break 
     # 
     # 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 
     #  pass 

if __name__ == '__main__': 
    main()