2

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.

9
  • 1
    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? Commented Mar 11, 2015 at 12:34
  • If you want to capture the current time at specific moments, you'll have to call datetime.now() to measure the current time. Commented Mar 11, 2015 at 12:35
  • I have to use it at multiple locations, makes the code look very messy. Commented Mar 11, 2015 at 12:35
  • Then put it in a function you call. Commented Mar 11, 2015 at 12:36
  • Wouldn't there be a time lag, between the function call and function output? Commented Mar 11, 2015 at 12:37

2 Answers 2

4

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()
Sign up to request clarification or add additional context in comments.

Comments

0

Move the t=... line into the for loop and/or condense it into the print statement and/or wrap it into a separate function then call that in the for loop.

The latter is going to be a best practice way of doing it if you're going to be using it in other places in the code. It means you only have to change the formatting or time call in a single place in your code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.