如何在 if 语句中使用本地时间 (HH:MM) - python

How to use localtime (HH:MM) in if statement - python

我在 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 的新手,但不是编码的新手。

您好, 泰斯

使用 datetime-对象进行所有计算:

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()

我不再使用内置的 datetime 库,它很糟糕。查看 arrow http://crsmithdev.com/arrow/

只需一个提示。

同时考虑使用 requests 它是在 python 中处理 http 内容的实际方式。

我已经尽可能多地重写了您的应用程序,并在下面提供了 link。我不太确定你打算把它放在哪里试图尽可能多地复制它但是。希望对您有所帮助。

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()