Home Python - Variables and Loops

# Python - Variables and Loops

Steve T
1#
Steve T Published in 2018-01-12 02:27:44Z
 i'm having some trouble getting my head around python i'm sure it's something simple but i just can't get it to work. What i'm trying to do is start my script with default variables. once it's processed then go to sleep for a set amount of time - then loop back through the script keeping any variables it's updated ( if any ) i can get it to work with the looping and i can get my counts to increase however i can't get my variable of date_time to update to the current time on the loop as it holds the time from when the script very first ran. Here is a base code I've been playing with to try and get to work with my main code but i cant get the base code to work the way i want it too import datetime import time date_time = datetime.datetime.now() redsent_time = '00:00:00.00' f = '%H:%M:%S.%f' tred = redsent_time tred2 = date_time.time() tred3 = str(tred2) #converts tred2 into a sting value instead of a command d1 = datetime.datetime.strptime(tred, f) d2 = datetime.datetime.strptime(tred3, f) def exec_code(): counter = 0 while True: if ((d2-d1).total_seconds()) >= 1: counter += 1 print((d2-d1).total_seconds()) print counter time.sleep(10) while exec_code(): pass  The result looks like this 37432.657 1 37432.657 2 37432.657 3 37432.657 4 37432.657 5  so you can see the time difference from midnight to my current time is always the same even though for each count 10 seconds has passed.
Barmar
2#
 You need to move the assignment of d2, and all the variables it depends on that could change, inside the loop. Otherwise, you're just repeatedly using the same value of d2, so of course you get the same time difference. import datetime import time date_time = datetime.datetime.now() redsent_time = '00:00:00.00' f = '%H:%M:%S.%f' tred = redsent_time d1 = datetime.datetime.strptime(tred, f) def exec_code(): counter = 0 while True: tred2 = date_time.time() tred3 = str(tred2) #converts tred2 into a sting value instead of a command d2 = datetime.datetime.strptime(tred3, f) if ((d2-d1).total_seconds()) >= 1: counter += 1 print((d2-d1).total_seconds()) print counter time.sleep(10) exec_code()