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.

Joer
  • 73
  • 1
  • 1
  • 5

2 Answers2

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

Torin M.
  • 523
  • 1
  • 7
  • 26
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)
Kirill Bulygin
  • 3,658
  • 1
  • 17
  • 23