Home > other >  Add a timestamp for a variable in python
Add a timestamp for a variable in python

Time:03-03

I have a function that does calculations over data in real time. I have some duplicates and I want to add timestamp for the first time I saw the duplicate and present the timestamp in the function. How to define the timestamp and how to find the firat time the duplicate has created?

def function_name(real_time_data):
    ...
    return dict([data1,data2]),time_created

CodePudding user response:

Take a look at the python datetime-module, especially the now()-function.

import datetime

time_created = datetime.datetime.now()

CodePudding user response:

You can use ctime from the time module like so:

def add(x, y):
    from time import ctime #import ctime
    var = x   y
    time_created = ctime() #get current time
    return var, time_created

print(add(1,2))

Output:

(3, 'Wed Mar  2 14:41:34 2022')

In this example we use ctime because it gives an easy to read str format.

We can apply this to your example like so:

def function_name(real_time_data):
    from time import ctime #import ctime
    ...
    return dict([data1,data2]), ctime()
  • Related