首页 > 解决方案 > 为打印功能添加时间戳

问题描述

我目前正在用 python 3.7 编写自己的程序,并希望在打印的前面添加一个时间戳,格式如下:

<hh:mm:ss> WhateverImPrinting

我查看了其他论坛,得到了一些使用 sys.stdout 的代码,使用 write 函数覆盖了文本。

我的问题是它在打印之前和之后都返回时间戳。

例如<14:21:51> Hello<14:21:51>

这应该是:

<14:21:51> Hello

我的代码:

old_f = sys.stdout  # Get old print output


class PrintTimestamp:
    # @staticmethod
    def write(self, x):
        old_f.write("<{}> {}".format(str(pC.Timestamp.hhmmss()), x))

    # @staticmethod
    def flush(self):
        pass


sys.stdout = PrintTimestamp()    # Set new print output

我在所有的课程和功能之后都运行了它,但在此之前if __name__ == '__main__'

标签: pythonpython-3.x

解决方案


您可以简单地覆盖printPython 3.x 中的函数:

from datetime import datetime

old_print = print

def timestamped_print(*args, **kwargs):
  old_print(datetime.now(), *args, **kwargs)

print = timestamped_print

然后

print("Test")

应该打印

2019-09-30 01:23:44.67890 Test

推荐阅读