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()
Share:
11,135

Related videos on Youtube

Tom Kurushingal
Author by

Tom Kurushingal

Updated on June 04, 2022

Comments

  • Tom Kurushingal
    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
      Martijn Pieters over 8 years
      Why 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
      Martijn Pieters over 8 years
      If you want to capture the current time at specific moments, you'll have to call datetime.now() to measure the current time.
    • Tom Kurushingal
      Tom Kurushingal over 8 years
      I have to use it at multiple locations, makes the code look very messy.
    • Martijn Pieters
      Martijn Pieters over 8 years
      Then put it in a function you call.
    • Tom Kurushingal
      Tom Kurushingal over 8 years
      Wouldn't there be a time lag, between the function call and function output?
    • Martijn Pieters
      Martijn Pieters over 8 years
      You 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
      Martijn Pieters over 8 years
      Or 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 using timeit.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
      Padraic Cunningham over 8 years
      t = lambda: datetime.now().strftime('%Y-%m-%d %H:%M:%S') print(t()) will also work.
    • jfs
      jfs over 8 years
      note: logging module can include the timestamp automatically in whatever time format you'd like.