4

The following condition does not work, any idea? Does Python think that 8am belongs to the same day and so this condition is not possible?

from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time >= time(23,00) and now_time <= time(8,00): 
    try:
        print 'hall light turning on'
    except:
        print 'Could not connect to Hue gateway'
DNA
  • 40,109
  • 12
  • 96
  • 136
Ossama
  • 2,169
  • 5
  • 38
  • 70

5 Answers5

14

How could the hour be simultaneously >= 23 and <= 8?

Try replacing and with or:

if now_time >= time(23,00) or now_time <= time(8,00):
    print "night"
Mark Ransom
  • 271,357
  • 39
  • 345
  • 578
4

Astral is a module that can give you a more accurate indication of "night time" based on the sun's current location. It's good when you want to automate turning lights on or off more efficiently by using dawn to dusk or sunset to sunrise and indicating what city you're in. Check out: https://astral.readthedocs.io/en/latest/

Sample Usage:

import pytz
from datetime import datetime
from astral import Astral
a = Astral()
city = a['Chicago'] # Replace with your city
now = datetime.now(pytz.utc)
sun = city.sun(date=now, local=True)
if now >= sun['dusk'] or now <= sun['dawn']:
    print "It's dark outside"
Mendhak
  • 7,168
  • 3
  • 46
  • 58
Kenny Ingle
  • 105
  • 6
1

To find out whether the Sun is up using ephem package:

#!/usr/bin/env python
import ephem # $ pip install ephem

observer = ephem.city('Beijing') # <-- put your city here
sun = ephem.Sun(observer)
sun_is_up = observer.previous_rising(sun) > observer.previous_setting(sun)
print('day' if sun_is_up else 'night')

The logic to determine day/night is from @miara's answer. To detect twilight, see Calculating dawn and sunset times using PyEphem.

Community
  • 1
  • 1
jfs
  • 346,887
  • 152
  • 868
  • 1,518
0

you could simplify it to this

if time(8, 00) <= now_time >= time(18, 00):

the full code below

from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if time(8, 00) <= now_time >= time(18, 00):
    try:
        print("hall light turning on")
    except:
        print("Could not connect to Hue gateway")
-1

Use this logic, to account for when you cross the day in the range:

  def is_time_in_range(start, end, x):
    #true if x is in range
    if start <= end:
         return start <= x <= end
    else:
         return start <= x or x <= end # Understand this part.

Sample Usage:

 import datetime
 start = datetime.time(23, 0, 0)
 end = datetime.time(8, 0, 0)
 is_time_in_range(start, end, datetime.time(23, 30, 0))
 is_time_in_range(start, end, datetime.time(09, 30, 0))

First call returns true second one returns false

sanjeev mk
  • 4,060
  • 4
  • 36
  • 60