You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

日出日落时段循环生成随机整数的代码优化:解决日落不停止问题

解决随机数生成程序日落不停止的问题

嘿,这个问题的核心确实是内层的while True死循环——一旦日出后进入这个循环,程序就再也不会去检查当前时间是否已经到日落了,而且原代码还只计算了启动当天的日出日落时间,第二天的时间也不会自动更新,这也是个潜在问题。

我给你调整一下代码,解决这两个问题:

from suntime import Sun, SunTimeException
import time
import datetime
import random

latitude = 51.51
longitude = -0.13
sun = Sun(latitude, longitude)

def get_today_sun_times():
    # 每天重新获取当天的日出日落时间(考虑夏令时/时区调整)
    try:
        today_sr = sun.get_sunrise_time() + datetime.timedelta(hours=1)
        today_ss = sun.get_sunset_time() + datetime.timedelta(hours=1) + datetime.timedelta(minutes=6)
        return today_sr, today_ss
    except SunTimeException:
        print("该纬度无法计算日出日落时间")
        return None, None

while True:
    # 每次循环开始先获取当天的日出日落时间
    sunrise, sunset = get_today_sun_times()
    if not sunrise or not sunset:
        time.sleep(3600)  # 出错就等1小时再试
        continue
    
    now = datetime.datetime.now(datetime.timezone.utc)
    # 检查当前是否在夜间:如果现在早于日出,或者晚于日落
    if now < sunrise or now > sunset:
        print(f"当前时间 {now.strftime('%H:%M')},夜间等待中...")
        time.sleep(60)  # 每分钟检查一次时间
        continue
    
    # 进入日间模式:生成随机数,每5秒检查一次时间
    print("日出啦!开始生成随机数...")
    while True:
        # 先检查当前时间是否还在日间
        now = datetime.datetime.now(datetime.timezone.utc)
        if now > sunset:
            print("日落了!停止生成随机数")
            break  # 跳出日间循环,回到外层的夜间等待
        
        # 生成并打印随机数(调整为你需求的0-20范围)
        print(random.randint(0, 20))
        time.sleep(5)

关键改动说明:

  • 每日更新日出日落时间:新增了get_today_sun_times函数,每次外层循环都会重新获取当天的日出日落时间,避免第二天时间失效的问题。
  • 用datetime对象直接比较时间:不再用字符串格式化后的时间比较,而是直接用UTC时间对象对比,避免字符串比较的潜在问题(比如跨零点的情况)。
  • 日间循环加入时间检查:每次生成随机数前先确认当前是否还在日落前,一旦到点就跳出日间循环,回到外层的夜间等待逻辑。
  • 异常处理:加入了SunTimeException的捕获,防止特殊纬度下无法计算日出日落导致程序崩溃。

这样修改后,不管你是日出前启动,还是运行到第二天,程序都会自动在日落时停止,次日日出时恢复生成随机数啦。

内容的提问来源于stack exchange,提问作者Schneggl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:39:46