niths4u
niths4u

Reputation: 440

python print statement with timestamp

My requirement is to have a function that works exactly like print but adds a timestamp at top. Currently I use something like:

def tprint(var):
    print(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))+" :: "+str(var))

Though it gives me all required output for a specific set – e.g.,

tprint("dummy"+" print")
2017-11-09 19:38:42 :: dummy print

I am not able to completely morph it for print statement. For example, tprint("hi","hello") and tprint("a =", a, sep='0', end='') fail.

My requirement is not to ideally make these two statements work. But to write an alternative function for print that works for all print arguments but gives an additional timestamp along with it. I am sure this may not be a straight forward solution. But do not want to miss if someone has already figured out any similar approach.

Upvotes: 0

Views: 4005

Answers (1)

pstatix
pstatix

Reputation: 3848

Edit:

After reviewing what you wanted, why not just pass your desired values to a function that uses the built-in print()? Like so:

def tprint(*args, **kwargs):
    stamp = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    print(stamp + ' :: ', *args, sep = kwargs['sep'], end = kwargs['end'])

a = 'Hello World'
tprint("a =", a, sep='0000', end='')

>>> [whatever the timestamp is] :: 0000a =0000Hello World

In order to provide a better response, I would really need to know what your expected output would be given an example. So far you have only said what does or does not work, but not why or how it should look.

Original Response:

Use the *args parameter in your function definition. It lets you supply an optional (unspecified) number of arguments in your function call and collects them into a list.

By definition, keyword arguments must come after all *args parameter. **kwargs packs them into a dictionary to iterate over. More information is available in this and that on SO.

So you can do something like this:

def tprint(*args, **kwargs):
    tempa = ' '.join(str(a) for a in args)
    tempk = ' '.join([str(kwargs[k]) for k in kwargs])
    temp = tempa + ' ' + tempk # puts a space between the two for clean output
    print(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + " :: " + temp)


a = 'Hello World!'

tprint("a =", a, sep='0', end='')

>>> 2017-11-09 09:35:37.148780 :: a = Hello World! 0 # I used datetime.datetime.now()

Upvotes: 3

Related Questions