如何使while循环在两个时间间隔之间工作



我正在尝试创建一个嵌套的while循环,它应该在02:20-21:50小时内工作,但我无法计算出满足条件的布尔表达式。

while True:
now = datetime.datetime.now()
print((now.hour >= 2 and now.minute >= 20), (now.hour <= 21 and now.minute <= 49))
while (now.hour >= 2 and now.minute >= 20) and (now.hour <= 21 and now.minute <= 49):
now = datetime.datetime.now()

这是我的代码,不幸的是它不起作用。例如,如果当前小时为17:50,则嵌套while循环将停止工作,因为now.minute = 50且大于49。这是我在测试时意识到的。也许这种情况的第一部分也以同样的方式得到了完美的解决。

如何使循环在02:20:00(上午(到21:49:59(晚上9:49:59(之间工作?

提前感谢您的帮助:(

now = datetime.datetime.now()
switch = !(2 <= now.hour <= 21) : True ? (20 <= now.minute <= 49)
while (2 <= now.hour <= 21) and switch:
now = datetime.datetime.now()

下面是一个如何做到这一点的例子。我使用了datetime对象的.replace()方法来防止显式设置日期时间对象的日、月、年值。

while True:
now = datetime.datetime.now()
start_time = datetime.datetime.now()
start_time.replace(hour=2, minute=20)
end_time = datetime.datetime.now()
end_time.replace(hour=21, minute=50)
while start_time < now < end_time:
now = datetime.datetime.now()

最新更新