Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Timestamp to Print Function

I am currently writing myself a program in python 3.7 and was wanting to add a timestamp to the front of my printing in the format:

<hh:mm:ss> WhateverImPrinting

I took a look at other forums and I get some code which used sys.stdout, overwriting the text using the write function.

My issue is it is returning the timestamp both before and after my print.

e.g. <14:21:51> Hello<14:21:51>

This should be:

<14:21:51> Hello

My code:

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

I have run this after all my classes and functions, but before if __name__ == '__main__'

like image 297
Bigfoot Blondy Avatar asked Sep 17 '25 07:09

Bigfoot Blondy


1 Answers

You can simply override print function in Python 3.x:

from datetime import datetime

old_print = print

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

print = timestamped_print

then

print("Test")

should print

2019-09-30 01:23:44.67890 Test
like image 107
Selcuk Avatar answered Sep 19 '25 07:09

Selcuk