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

2024-04-20 03:17:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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公司


Tags: andimportdatetimeif时间dt语句be
2条回答

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

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

只要一个提示。在

还要研究一下使用requests这是在python中处理http内容的实际方法。在

我已经重写了你的应用程序,我可以提供以下链接。我不太确定你的目标是什么,普特试图尽可能复制它,但是。我希望这有帮助。在

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

相关问题 更多 >