Home > Enterprise >  How to make while loop work inbetween time interval?
How to make while loop work inbetween time interval?

Time:10-29

I am trying to create a nested while loop which should be working in hours 02:20 - 21:50, butI can't figure out the boolean expression which would fulfill the condition.

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()

This is my code, unfortunately it doesn't work. For example if the current hour is 17:50 the nested while loop will stop working because now.minute = 50 and is greater than 49. This is what I've realised while testing it rn. Perhaps the first part of the condition is also flawled in the same way.

How can I make the loop work between 02:20:00(a.m.) till 21:49:59(9:49:59 p.m.)?

Thank you for your help in advance :)

CodePudding user response:

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()

CodePudding user response:

Here is an example how to do it. I used the .replace() method of the datetime object to prevent setting the datetime objects' values explicitly.

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()
  • Related