以下情况不起作用,有什么想法吗? Python认为8am属于同一天,所以这种情况不可能吗?
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'
答案 0 :(得分:10)
小时怎么可能同时&gt; = 23和&lt; = 8?
尝试将and
替换为or
:
if now_time >= time(23,00) or now_time <= time(8,00):
print "night"
答案 1 :(得分:3)
Astral是一个模块,可以让您更准确地指示夜晚&#34;基于太阳的当前位置。如果您希望通过黎明到黄昏或日落到日出来更有效地自动打开或关闭灯光,并指出您所在的城市,那就太好了。查看:http://pythonhosted.org/astral/
样本用法:
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"
答案 2 :(得分:0)
要了解太阳是否正在使用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')
确定日/夜的逻辑来自@miara's answer。要检测黄昏,请参阅Calculating dawn and sunset times using PyEphem。
答案 3 :(得分:0)
您可以将其简化为此
if time(8, 00) <= now_time >= time(18, 00):
下面的完整代码
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")
答案 4 :(得分:-1)
使用此逻辑来说明您在范围内过了一天的时间:
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.
样本用法:
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))
第一次调用返回true
第二次返回false