简体   繁体   中英

While loop is not breaking python

I am currently trying to compare the current date and time to a date and time which are written down in another file. For some weird reason the while loop is not breaking but creating an endless loop.

This is what the test.txt file I try to compare the current date and time with contains: 29.10.2021 20:47:47

This is my code (Imagine ga is equal to the data in the test.txt ):

import time
from datetime import datetime
from datetime import timedelta

def background_checker():
    with open('test.txt','r+') as sample:
        while True:
            ga = datetime.now()
            ga = ga.strftime('%d.%m.%Y %H:%M:%S')
            print(ga, end='\r')
            line = sample.readline()
            if line == ga:#if time and date in file equal to the current time and date, the if statement should be triggered. 
                print('alarm')
                break
background_checker()

Am I doing something wrong in my code? If so I would be very glad if someone could explain to me what I've made wrong and how I can solve this problem.

You are trying to create an alarm program but you're comparing strings using string equality. A better approach is to compare datetime objects.

import time
from datetime import datetime
from datetime import timedelta

def background_checker():
    format = '%d.%m.%Y %H:%M:%S'
    with open('test.txt','r+') as sample:
        while True:
            ga = datetime.now()
            print(ga)
            line = sample.readline()
            alarm_time = datetime.datetime.strptime(line, format)     
            if ga > alarm_time: #if time and date in file equal to the current time and date, the if statement should be triggered. 
                print('alarm')
                break
background_checker()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM