Reputation: 23
I want to print the current time on screen in hours and minutes that updates automatically without making a new line, as well as print another line with the seconds that also updates automatically on a second line. Thanks in advance! This is what I have so far:
import time
from datetime import datetime
while True:
now = datetime.now()
current_time = now.strftime("%I:%M %p")
current_second = now.strftime("%S")
print("\r" + "Clock: ", current_time, end= ' ')
print("\r" + "\n" + "Seconds: ", current_second, end=' ')
time.sleep(1)
This is what the output looks like: Output
The seconds out like they should, but the time does not
Upvotes: 2
Views: 1271
Reputation: 2266
Combining @Rhuamer's answer with your code, you can do something like:
import subprocess
import sys
import time
from datetime import datetime
clear = "cls" if sys.platform == "win32" else "clear"
while True:
now = datetime.now()
current_time = now.strftime("%I:%M %p")
current_second = now.strftime("%S")
print(f"\rClock: {current_time}", flush=True, end="\n")
print(f"Seconds: {current_second}", flush=True, end="")
time.sleep(1)
subprocess.run(clear, shell=True)
Upvotes: 1
Reputation: 13087
The heart of this question is based around how to clear the console and there are a number of good answers here Clear terminal in Python and I recommend you explore it. The other part of the question deals with writing on multiple lines and so I feel this is not quite a duplicate.
I think the easiest way to get what you seek might be to use an f-string and simply do:
import time
from datetime import datetime
while True:
now = datetime.now()
current_time = now.strftime("%I:%M %p")
current_second = now.strftime("%S")
print(f"\033cClock: {current_time}\nSeconds: {current_second}")
time.sleep(1)
If that does not quite work correctly, there are other more slightly extended escape codes you can explore such as \033c\033[3J
. I have tested the \033c
on a few terminals with success though.
If after reviewing that other question, you feel this is a duplicate, just let me know and I will remove this answer and you can close the question.
Upvotes: 1
Reputation: 68
Try clearing the console with a clear method. Define it like this:
from os import system, name
if name == "nt":
clear = lambda: system("cls")
else:
clear = lambda: system("clear")
and then just call it every loop
Upvotes: 1