1

In Python how could I accomplish printing out the time in realtime in a Terminal?

while(True):
    print("[ " + "Time: " + datetime.date.today().strftime("%Y-%m-%d") + " ]")

The code above will just print out the line infinite amount of times. How can I do a "static" line of text and refresh the time every second without doing print statements on every line? Hope this wasn't too confusing :)

Wasn't sure what to search for, it didn't give me the result I was looking for.

0

2 Answers 2

0

By default, print outputs \n (or \r\n on Windows) at the end of the line to move to the New line. You just need to output \r instead in order to Return to the beginning of the current line (and sleep for a second before outputting again at the same line):

import time, datetime
while True:
    s = datetime.datetime.now().strftime('[ Time: %Y-%m-%d %H:%M:%S ]')
    print(s, end='\r')
    time.sleep(1)
Sign up to request clarification or add additional context in comments.

Comments

0
import sys
import datetime

while(True):
    sys.stdout.write("\r" + "[ " + "Time: " + datetime.date.today().strftime("%Y-%m-%d") + " ]")    
    sys.stdout.flush()

You can try this library

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.