Man of few words said on the first piece of code
import time from datetime import datetime as dt for i in range(5): print(dt.now()) time.sleep(1)
The output is:
2019-07-31 11:40:00.334841 2019-07-31 11:40:01.335235 2019-07-31 11:40:02.335700 2019-07-31 11:40:03.335846 2019-07-31 11:40:04.336174
Visible print a message each time another will be played under a line of print, this is why?
Let's execute code help (print) statement to get the following information
Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
Visible each time the print function, the end will perform a line feed. If we want every new time information output at the same time covering the original information how to do it?
Then we can use sys.stdout.write function:
import time from datetime import datetime as dt import sys while True: sys.stdout.write('\r{0}'.format(dt.now())) sys.stdout.flush() time.sleep(1)
effect:
2019-07-31 13:45:15.537898
A time line will update every second