Adding a datetime stamp to Python print

An alternative solution that the timestamp is the beginning (prepended) instead of end (appended):

from datetime import datetime as dt 

old_out = sys.stdout

class StAmpedOut:
  """Stamped stdout."""
    
  nl = True
  
  def write(self, x):
    """Write function overloaded."""
      if x == '\n':
        old_out.write(x)
        self.nl = True
      elif self.nl:
        old_out.write('%s> %s' % (str(dt.now()), x))
        self.nl = False
      else:
        old_out.write(x)
    
sys.stdout = StAmpedOut()

As you can’t override the write function (it's read-only) a simple monkey-patch could look like this (appending the timestamp to every printed line):

old_f = sys.stdout
class F:
    def write(self, x):
        old_f.write(x.replace("\n", " [%s]\n" % str(datetime.now())))
sys.stdout = F()

An example would the look like this:

>>> print "foo"
foo [2011-02-03 09:31:05.226899]