[Python][Def] Print with Date / String with Date

A very simple Python definition you can use so that your printed output has a time and date stamp.

Print with date

def pwd(string):
  import datetime
  print(str(datetime.datetime.now()).split('.',1)[0] + ": " + string)


String with date

This one is where you just want to string modified to have a date infront of it.

def swd(string):
  import datetime
  return(str(datetime.datetime.now()).split('.',1)[0] + ": " + string)


Print and Log

This is even more useful (a bit like something I used in PowerShell a lot.) This is where you want to print to screen and log at the same time. I've moved the 'import datetime' outside the def. And you'll need to define a variable logfile = "mylogfile.txt".

import datetime
logfile = "mylogfile.txt"
def printLog(string):
  output = (str(datetime.datetime.now()).split('.',1)[0] + ": " + string)
  open(logfile,'a').write(output + "\n")

Note: When your script runs, you'll probably first want to delete the logfile, otherwise it will append forever. This can be done with:

import os
if os.path.exists(logfile): os.remove(logfile)


Examples

pwd("Test")

test = swd("Test")

print(test)

printLog("Print and log!")





Comments