How to create timestamp variable in Python?
11,135
You cannot avoid having to call datetime.now()
if you need to capture the current time at different moments.
Put the call in a function if you feel it is too verbose to repeat:
def current_time():
return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
then call that:
for i in range(5):
time.sleep(2)
print current_time()
Related videos on Youtube
Author by
Tom Kurushingal
Updated on June 04, 2022Comments
-
Tom Kurushingal over 1 year
I am trying to create a timestamp variable which actually stores the present time and outputs the time at that instance. A reproducible code is also included:
import time from datetime import datetime t = datetime.now().strftime('%Y-%m-%d %H:%M:%S') for i in range(5): time.sleep(2) print t
Output
2015-03-11 11:28:53 2015-03-11 11:28:53 2015-03-11 11:28:53 2015-03-11 11:28:53 2015-03-11 11:28:53
Desired output
2015-03-11 11:28:53 2015-03-11 11:28:55 2015-03-11 11:28:57 2015-03-11 11:28:59 2015-03-11 11:29:01
Any easy way to do this instead of placing the command
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
multiple times in the code.
-
Martijn Pieters over 8 yearsWhy would a string object update itself in a loop? Why not simply use
print datetime.now().strftime('%Y-%m-%d %H:%M:%S')
in the loop itself? -
Martijn Pieters over 8 yearsIf you want to capture the current time at specific moments, you'll have to call
datetime.now()
to measure the current time. -
Tom Kurushingal over 8 yearsI have to use it at multiple locations, makes the code look very messy.
-
Martijn Pieters over 8 yearsThen put it in a function you call.
-
Tom Kurushingal over 8 yearsWouldn't there be a time lag, between the function call and function output?
-
Martijn Pieters over 8 yearsYou are printing time at the second level and you are worried about the overhead of calling a function? We are talking nanoseconds here.
-
Martijn Pieters over 8 yearsOr to put it another way: if you are worried about the overhead of calling a function, why are you creating a new
datetime
object then formatting that object to a string each time? Why are you not usingtimeit.default_time
and worry about converting that number to a precise timestamp later? Why are you using Python at all if this is time critical? -
Padraic Cunningham over 8 years
t = lambda: datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(t())
will also work. -
jfs over 8 yearsnote:
logging
module can include the timestamp automatically in whatever time format you'd like.
-