Python: Modulo for string formatting Issue (Date and Time Lesson Inquiry)


#1

Hello Community,

I have an issue with one of the early python lessons: Date and Time. I was taught to use Modulo for formatting a string related to Date and Time. The following is what I was taught:


print '%s/%s/%s' % (now.hour, now.minute, now.second)

Unfortunately, when I attempt to use this code on Python, it doesn’t work. Below is the code I input and the proceeding message from Python.

print ‘%s/%s/%s’ % (now.hour, now.minute, now.second)
SyntaxError: invalid syntax

Can someone please explain why it doesn’t work for me?

Thank you in advance.


#2

Use colons as delimiters rather than slashes for the time components.

Is there a problem on the preceding line of code?


#3

I changed the code to look as follows:

print ‘%s:%s:%s’ % (now.hour, now.minute, now.second)

However, Python still returns the same error message:

SyntaxError: invalid syntax

It also highlights the end quote (’) after the last %s

Also, I’m using Python version 3.6.2 for Mac.


#4

What lines of code precede the one that you posted?

A syntax error sometimes relates to lines that precede the one on which it is identified.


#5

There is nothing proceeding. Please see below picture:


#6

There is nothing proceeding. Please see below picture with single quotation marks:


#7

The second screen capture reveals that you used invalid single-quote marks.

Since you are using Python 3.6.2, rather than a version of Python 2, print is a function, therefore the expressions to be evaluated for output must be enclosed in parentheses.

You are also missing some statements, including a necessary import statement.

For the version of Python you are using, try the following instead of what is prescribed by Codecademy’s Hot Date exercise …

from datetime import datetime
now = datetime.now()
print('%02d:%02d:%02d' % (now.hour, now.minute, now.second))

The above code corrects the SyntaxError and also improves upon the Codecademy exercise by padding each time component with a leading 0 in cases where that is needed to guarantee that the time components all consist of two digits.

Example output …

19:34:08

EDITED on August 30, 2017 to supply recommended code for Python 3.6.2


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.