清除Python

时间:2017-03-29 00:28:59

标签: python-3.x datetime-format python-datetime

所以,我是Python和编程的超级新手。我还在学习最基本的命令和术语。我的问题是我试图在无限循环中打印日期时间,但只在一行上。

我希望shell中的输出显示日期和时间,然后清除先前显示的日期时间并将其替换为新值。我似乎无法弄清楚我错过了什么,并通过阅读不同的问题,我似乎无法找到我正在寻找的东西。任何想法,帮助或指导将不胜感激。在这一点上,尝试阅读Python文档并没有帮助我。这是我到目前为止所发现的:

import datetime
import time

while True:
    today = datetime.date.today()
    now = datetime.datetime.now()
    print ("The Current date is ", (today.strftime('%m/%d/%Y')))
    print ("The Current Time is ", (now.strftime('%H:%M')))
    time.sleep(30)

这生成:

The Current date is  03/28/2017
The Current Time is  19:09
The Current date is  03/28/2017
The Current Time is  19:10

我想说:

The Current date is  03/28/2017
The Current Time is  19:09

然后,删除上面的文字并替换为

The Current date is  03/28/2017
The Current Time is  19:10

日期时间屏幕截图

1 个答案:

答案 0 :(得分:0)

一种方法是使用ANSI escape sequences

import datetime
import time
import sys

while True:
    today = datetime.date.today()
    now = datetime.datetime.now()
    print ("The Current date is ", (today.strftime('%m/%d/%Y')))
    print ("The Current Time is  ", (now.strftime('%H:%M')))
    sys.stdout.write("\033[F") # Cursor up one line
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(30)

另一种选择:

导入日期时间 进口时间 import os

while True:
    today = datetime.date.today()
    now = datetime.datetime.now()
    print ("The Current date is ", (today.strftime('%m/%d/%Y')))
    print ("The Current Time is ", (now.strftime('%H:%M')))
    time.sleep(30)
    os.system('clear')