我每分钟都要检查一下时间,但是没有一个好方法可以检查我是否已经在这个时间内进行了检查。操作模式。我想成为' on'白天前2小时到日落前1小时。如果我继续使用next_rising()
和next_setting()
进行检查,那么在太阳升起的那一刻,我的逻辑似乎失败了,因为在那之后它开始计算明天的日出。我的is_daytime()
已被破坏。
def is_daytime():
"""
Returns whether we should operate in the 'daytime' mode. Note that this
mode is shifted earlier to begin before sunrise and end before sunset.
"""
# Get the localized hour of the day
now = datetime.datetime.now()
# Get the next sunrise/sunset
here.date = now
sunrise = ephem.localtime(here.next_rising(ephem.Sun))
sunset = ephem.localtime(here.next_setting(ephem.Sun))
sunrise_shift = datetime.timedelta(hours=START_BEFORE_SUNSRISE_HR)
sunset_shift = datetime.timedelta(hours=END_BEFORE_SUNSET_HR)
# Return whether it is some amount of time before sunrise AND sunset
return ((sunrise - now) < sunrise_shift) and ((sunset - now) < sunset_shift)
# Dependencies
import time
import datetime
import pytz
import ephem
# Choose your location for sunrise/sunset calculations
MY_TIMEZONE = "America/Los_Angeles"
MY_LONGITUDE = '37.7833' # +N
MY_LATITUDE = '-122.4167' # +E
MY_ELEVATION = 0 # meters
# Choose when to start and stop relative to sunrise and sunset
START_BEFORE_SUNSRISE_HR = 1
END_BEFORE_SUNSET_HR = 1
here = ephem.Observer()
def is_daytime():
"""
Returns whether we should operate in the 'daytime' mode. Note that this
mode is shifted earlier to begin before sunrise and end before sunset.
Assumes sunset NEVER comes after midnight
"""
# Get the localized hour of the day
now = datetime.datetime.now()
# Get the next sunrise/sunset
here.date = now
next_sunrise = ephem.localtime(here.next_rising(ephem.Sun()))
next_sunset = ephem.localtime(here.next_setting(ephem.Sun()))
sunrise_shift = datetime.timedelta(hours=START_BEFORE_SUNSRISE_HR)
sunset_shift = datetime.timedelta(hours=END_BEFORE_SUNSET_HR)
# If it's daytime
if (next_sunset < next_sunrise):
return (now < (next_sunset - sunset_shift))
# Otherwise it's nighttime
else:
return ((next_sunrise - sunrise_shift) < now)
def main():
# Configure the timezone
pytz.timezone(MY_TIMEZONE)
# Configure the ephem object
here.lat = MY_LATITUDE
here.lon = MY_LONGITUDE
here.elevation = MY_ELEVATION
while True:
if is_daytime():
print "It's daytime!"
time.sleep(60)
if __name__ == '__main__':
main()
答案 0 :(得分:3)
太阳升起的那一刻,我的逻辑似乎失败了,因为在那之后它开始计算明天的日出。
通过逻辑思考。有什么案例?
<= sunrise-2H
; sunset-1H
的检查无关紧要,但无害。<= sunset-1H
;对sunrise-2H
的检查不仅无关紧要,而且有害。那么,你怎么知道你在哪个案子?简单。如果sunset > sunrise
,则为1或3;只需检查sunrise-2H
;否则,你是2,只需检查sunset-1H
。
如果你比Oulo向北更远怎么办?例如,在6月初的罗瓦涅米,下一个日落是一个月之后。这是否意味着您希望您的计划在整个月都停留?或者你想选择一个任意的时间来启动和关闭(例如,在“午夜”前2小时开始并在一小时后结束)?无论你提出什么规则,我认为ephem
有足够的数据供你编写。或者,如果您不知道,至少测试代码并查看 应用的规则,以便您可以记录。 (我猜测那些住在那里的人习惯于查看与此相关的时间相关程序的文档......)