4

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__'

2 Answers 2

16

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
Sign up to request clarification or add additional context in comments.

Comments

0

Here you go.

from datetime import datetime

class PrintTimeStamp():
   def write(self,x):
       ts = str(datetime.now.hour())+":"+str(datetime.now().minute)+":"+str(datetime.now().second)
       print("<{}> {}".format(str(ts),x)

pts = PrintTimeStamp()
pts.write("test")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.