1

I am creating a program for Raspberry Pi where, in Command Line, the program displays the date and time as shown below and I want to add a repeat or update so the date and time are current after the program begins. This code came off a online tutorial and I want to mess around with it and hit a dead end. I am currently learning Python.

#!/usr/bin/python

import time
now = time.strftime("%c")
print "current date and time " + time.strftime("%c")
8
  • because you need to delete In [5]:. It was just showing the work from ipython. All you need is datetime.datetime.now() and assign that for variable if you like. Commented Dec 11, 2015 at 8:13
  • And line with Out [5]: ... Commented Dec 11, 2015 at 8:21
  • '#!/usr/bin/python import time now = time.strftime("%c") print "current date and time " + time.strftime("%c") import datetime datetime.datetime.now() datetime.datetime.now() datetime.datetime(2015, 12, 11, 11, 0, 37, 518511)' it doesn't update Commented Dec 11, 2015 at 8:29
  • see edited answer. It doesn't updated because it's too quick, only microseconds could be displayed Commented Dec 11, 2015 at 8:34
  • Related: python: how to overwrite the previous print to stdout Commented Dec 11, 2015 at 9:01

3 Answers 3

2

The following code will print time in the same place every second:

import time

while True:
    time.sleep(1.0)
    print("\r" + str(time.time()), end="")
Sign up to request clarification or add additional context in comments.

3 Comments

I have tried the code separately and the equal sign in the final line is apparently a syntax error.
Are you using python 2 or 3?
I am using python 2.7
0

I think this has been answered before here:

You can use a trailing comma to avoid a newline being printed:

print "this should be",
print "on the same line"

Comments

0

You could use datetime module:

import datetime
datetime.datetime.now()

In [5]: datetime.datetime.now()
Out[5]: datetime.datetime(2015, 12, 11, 11, 0, 37, 518511)

EDIT

Try to use following script

#!/usr/bin/python
import datetime
import time

a = datetime.datetime.now()
time.sleep(1)
b = datetime.datetime.now()
print(b-a)

5 Comments

Would that update the time repeatedly until program is closed?
Of course. You could try that several times in python console and will see the results
Thank you. This helps very much.
I have hit a slight problem. It keeps saying syntax error for line 3. Not sure if that is just me.
@J.Gill could you post that line and edit question for that?

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.