Good afternoon. I have code in Python:
while (time.time() - start_time) < 10:
current_date_time = time.strftime("%Y-%m-%d %H:%M:%S")
current_time = time.strftime("%H:%M:%S")
print("\r" + current_date_time)
print(current_time, end="\r")
time.sleep(0.5)
I want to get:
cycle1:
line1: data1
line2: data2
cycle2:
line1: data3
line2: data4
...
cycleN:
line1: dataN
line2: dataN+1
but i have now only:
2023-05-12 14:25:24 (data1)
2023-05-12 14:25:25 (data3)
2023-05-12 14:25:25 (data5)
2023-05-12 14:25:26 (data6)
14:25:26 (data7)
The problem is print1 which is not overwrited (i can not get back 1 line UP). How can i correct the code to get desired result?
Thank you in advance for help the newbie.
I try to use print(..., end='') or print(..., end='/r').
I want to get:
cycle1:
line1: data1
line2: data2
cycle2:
line1: data3
line2: data4
...
cycleN:
line1: dataN
line2: dataN+1
===========================================================
My solution code:
import datetime
import time
import colorama
from colorama import Fore, Style
def main():
# Initialize colorama
colorama.init()
# Get the current time
start_time = time.time()
# Set cycle time length in seconds
cycle_length = 10
while (time.time() - start_time) < cycle_length:
# Get the current date and time
now = datetime.datetime.now()
date_time_str = now.strftime("%Y-%m-%d %H:%M:%S")
time_str = now.strftime("%H:%M:%S")
# Clear the screen
print("\033c", end="")
# Print the date and time
print(Fore.GREEN + date_time_str)
print(Fore.YELLOW + time_str)
# Sleep for 500 milliseconds
time.sleep(0.5)
# Clear the date and time
print("\033[2K", end="")
print("\033[F", end="")
print("\033[2K", end="")
print("\033[F", end="")
# Sleep for 500 milliseconds
time.sleep(0.5)
# Wait for a key press to exit
if time.time() - start_time >= cycle_length:
# Clear the first line (stayed after exit before CLI)
print("\033[2K", end="")
print("\033[F", end="")
break
# Reset colorama
colorama.deinit()
if __name__ == "__main__":
main()