PYTHON IF ELIF DATETIME, what's the error in my datetime code? Works if i rerun the code but if i let it run normaly, the hours updated gimme a 24h

Question:

On my code, the label lb1 should be updated everytime it reaches the time target that shows if the bot is running and the time left until it stops, and if its not running shows the time left until it will start. Works normal if I stop the code and run again when the time hit the target, but if i don’t stop, instead of showing me the time left until the next target, it shows me an 24 hours or 14 hours countdown in the label. What am i doing wrong?
Here’s the full source code:

import pyautogui
from tkinter import *
import win32gui
import datetime
from time import sleep

# Get screen monitor and Windows Taskbar size, Libraries used: pyautogui, win32gui
taskbar_hwnd = win32gui.FindWindow("Shell_TrayWnd", None)
taskbar_rect = win32gui.GetWindowRect(taskbar_hwnd)
print("Left:", taskbar_rect[0], "Top:", taskbar_rect[1], "Width:", taskbar_rect[2]-taskbar_rect[0], "Height:", taskbar_rect[3]-taskbar_rect[1])
task_height = taskbar_rect[1]

width, height = pyautogui.size()
print(width)

# Get the current time
current_time = datetime.datetime.now().time()

# Define the target times
first_morning_target = datetime.time(10, 0)
second_morning_target = datetime.time(12, 0)
first_afternoon_target = datetime.time(16, 0)
second_afternoon_target = datetime.time(18, 0)
first_night_target = datetime.time(20, 00)
second_night_target = datetime.time(0, 0)


# Check the current time and determine which target time to use
if current_time < first_morning_target:
    target_time = first_morning_target
    target_time_text = "10 AM"
elif first_morning_target <= current_time < second_morning_target:
    target_time = second_morning_target
    target_time_text = "12 PM"
elif second_morning_target <= current_time < first_afternoon_target:
    target_time = first_afternoon_target
    target_time_text = "4 PM"
elif first_afternoon_target <= current_time < second_afternoon_target:
    target_time = second_afternoon_target
    target_time_text = "6 PM"
elif second_afternoon_target <= current_time < first_night_target:
    target_time = first_night_target
    target_time_text = "8 PM"
elif first_night_target <= current_time < second_night_target:
    target_time = second_night_target
    target_time_text = "midnight"
else:
    target_time = first_morning_target
    target_time_text = "10 AM"

# Calculate the time difference between the current time and the target time
time_diff = datetime.datetime.combine(datetime.date.today(), target_time) - datetime.datetime.now()

# Get the remaining minutes after dividing the total seconds by 3600 (seconds in an hour)
remaining_minutes = time_diff.seconds % 3600 // 60


# Tkinter GUI
root = Tk()
root.geometry("{}x{}+{}+{}".format(width, 20, 0, task_height - 20))
root.overrideredirect(True)
root.attributes('-topmost', True)

# lb1 The Label that would be updated if the bot is on or off
lb1 = Label(root, text='Loading...', bg='blue', fg='white', font=('Montserrat semibold', 8))
lb1.place(x=0, relwidth=1)

root.update()



# Logic
while True:
    current_time = datetime.datetime.now().time()
    # Calculate the time difference between the current time and the target time
    time_diff = datetime.datetime.combine(datetime.date.today(), target_time) - datetime.datetime.now()

    # Get the remaining minutes after dividing the total seconds by 3600 (seconds in an hour)
    remaining_minutes = time_diff.seconds % 3600 // 60
    remaining_seconds = time_diff.seconds % 3600 % 60
    if (first_morning_target <= current_time < second_morning_target) or (
            first_afternoon_target <= current_time < second_afternoon_target) or (
            first_night_target <= current_time < second_night_target):
        # Print the time difference in hours and minutes
        sleep(1)
        hour1 = f"{current_time.strftime('%I:%M %p')} Bot awake, {time_diff.seconds // 3600} hour(s), {remaining_minutes} minute(s) e {remaining_seconds} second(s) for the bot to finish"
        lb1.config(text=hour1, bg='#2dff26')
        root.update()
    else:
        sleep(1)
        hour2 = f"{current_time.strftime('%I:%M %p')} Bot resting, {time_diff.seconds // 3600} hour(s), {remaining_minutes} minute(s) e {remaining_seconds} second(s) for the bot to start"
        lb1.config(text=hour2)
        root.update()
Asked By: BOB CÃOMUNISTA

||

Answers:

All the code that calculates target_time and the time differences depending on it should be inside the loop, so it gets updated whenever you pass the target and need to calculate a new target.

And in your elif statements you don’t need to test that you’re >= the previous target, since you only get to elif if the current time isn’t less than the previous target.

import pyautogui
from tkinter import *
import win32gui
import datetime
from time import sleep

# Get screen monitor and Windows Taskbar size, Libraries used: pyautogui, win32gui
taskbar_hwnd = win32gui.FindWindow("Shell_TrayWnd", None)
taskbar_rect = win32gui.GetWindowRect(taskbar_hwnd)
print("Left:", taskbar_rect[0], "Top:", taskbar_rect[1], "Width:", taskbar_rect[2]-taskbar_rect[0], "Height:", taskbar_rect[3]-taskbar_rect[1])
task_height = taskbar_rect[1]

width, height = pyautogui.size()
print(width)

# Define the target times
first_morning_target = datetime.time(10, 0)
second_morning_target = datetime.time(12, 0)
first_afternoon_target = datetime.time(16, 0)
second_afternoon_target = datetime.time(18, 0)
first_night_target = datetime.time(20, 00)
second_night_target = datetime.time(0, 0)

# Tkinter GUI
root = Tk()
root.geometry("{}x{}+{}+{}".format(width, 20, 0, task_height - 20))
root.overrideredirect(True)
root.attributes('-topmost', True)

# lb1 The Label that would be updated if the bot is on or off
lb1 = Label(root, text='Loading...', bg='blue', fg='white', font=('Montserrat semibold', 8))
lb1.place(x=0, relwidth=1)

root.update()

# Logic
while True:
    current_time = datetime.datetime.now().time()

    # Check the current time and determine which target time to use
    if current_time < first_morning_target:
        target_time = first_morning_target
        target_time_text = "10 AM"
    elif current_time < second_morning_target:
        target_time = second_morning_target
        target_time_text = "12 PM"
    elif current_time < first_afternoon_target:
        target_time = first_afternoon_target
        target_time_text = "4 PM"
    elif current_time < second_afternoon_target:
        target_time = second_afternoon_target
        target_time_text = "6 PM"
    elif current_time < first_night_target:
        target_time = first_night_target
        target_time_text = "8 PM"
    elif current_time < second_night_target:
        target_time = second_night_target
        target_time_text = "midnight"
    else:
        target_time = first_morning_target
        target_time_text = "10 AM"

    # Calculate the time difference between the current time and the target time
    time_diff = datetime.datetime.combine(datetime.date.today(), target_time) - datetime.datetime.now()

    # Get the remaining minutes after dividing the total seconds by 3600 (seconds in an hour)
    remaining_minutes = time_diff.seconds % 3600 // 60
    remaining_seconds = time_diff.seconds % 3600 % 60
    if (first_morning_target <= current_time < second_morning_target) or (
            first_afternoon_target <= current_time < second_afternoon_target) or (
            first_night_target <= current_time < second_night_target):
        # Print the time difference in hours and minutes
        sleep(1)
        hour1 = f"{current_time.strftime('%I:%M %p')} Bot awake, {time_diff.seconds // 3600} hour(s), {remaining_minutes} minute(s) e {remaining_seconds} second(s) for the bot to finish"
        lb1.config(text=hour1, bg='#2dff26')
        root.update()
    else:
        sleep(1)
        hour2 = f"{current_time.strftime('%I:%M %p')} Bot resting, {time_diff.seconds // 3600} hour(s), {remaining_minutes} minute(s) e {remaining_seconds} second(s) for the bot to start"
        lb1.config(text=hour2)
        root.update()
Answered By: Barmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.