Search code examples
pythonpython-2.7if-statementlocaltime

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


I made some code to turn on a light depending on movement and the time of the day in an if statement. If the (local)time is between sunrise and a preset time or sunset and a preset time the if statement is true and the motion detection statements will follow.

At the moment the time is only presented in hours as an integer. How can i make my if statement to work with hours and minutes (think this will need to be a string). So the statement will work with 6:45 instead of 7 for example.

Here is my code.

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

I would like to hear your thoughts. Little note I'm new to python but not to coding.

Greetings, Thijs


Solution

  • Do all calculations with 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()