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__'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With