""" Combine both the date and the time with a space and separate the time digits with : and the date digits with /. The date must come before the time."""
from datetime import datetime
now = datetime.now()
print ('% mm / % dd / % yyyy' '% hh : % mm : ss') (now.month, now.day, now.year now.hour, now.minute, now.second)
好的,我正在做的是尝试完成一个我从www.codecademy.com上停留的课程,我在Python v2.7.9中编写脚本。我不断得到如下错误:
File "python", line 9
print ('% mm / % dd / % yyyy' '% hh : % mm : ss') (now.month, now.day, now.year now.hour, now.minute, now.second)
SyntaxError: invalid syntax
我无法弄清楚出了什么问题,以及我是如何解决它的。如果有人能帮助我,我会非常感激。
答案 0 :(得分:1)
问题出在括号组之间。
这是字符串格式的错误语法:
print ('% mm / % dd / % yyyy' '% hh : % mm : ss') (now.month, ...
旧式格式化需要百分号,新格式字符串格式需要.format
。
您要做的是:
print '%d / %d / %d' '%d : %d : %d'%(now.month, now.day, now.year now.hour, now.minute, now.second)
# --- note the percent sign here -^-
因为你正在做一个代码学习课程,所以我不会带走学习知识,但你可以在Python string formatting to get a final solution上阅读更多关于如何最好地格式化你的字符串的内容。
答案 1 :(得分:0)
不确定你在尝试使用那些奇怪的print
做了什么,但我想它会是这样的:
>>> print('%2s / %2s / %4s %2s : %2s : %2s' % (now.month, now.day, now.year, now.hour, now.minute, now.second))
12 / 23 / 2014 19 : 24 : 38
然而,更好的方法是使用.strftime
datetime
个now
实例的>>> print(now.strftime('%m/%d/%Y %H:%M:%S'))
12/23/2014 19:24:38
方法进行格式设置:
strftime
请注意这是多么简洁和可读。如果你坚持使用那些奇怪的额外空格,你可以随时将它们添加到你传递给{{1}}的格式字符串中: - )