简体   繁体   English

Python 2.7字符串格式

[英]Python 2.7 string format

from datetime import datetime
now = datetime.now()
sentence = "{:%B %d %Y}".format(now=datetime.now)

If for some reason I have to use an import from keyword how would I format this in three lines like the example above? 如果由于某种原因我必须使用关键字from的import,如何像上面的示例一样在三行中设置其格式? My exact question is I don't know how to use the format parameters in this case. 我的确切问题是在这种情况下我不知道如何使用格式参数。

  1. You need pass datetime.now() , not datetime.now method itself. 您需要传递datetime.now() ,而不是datetime.now方法本身。
  2. specify now in the format string to use the keyword argument. now在格式字符串中指定以使用关键字参数。 Or you can omit now if you pass the datetime object as a positional argument. 或者,如果您将datetime对象作为位置参数传递,则now可以省略。

>>> from datetime import datetime
>>> now = datetime.now()
>>> "{now:%B %d %Y}".format(now=datetime.now())  # keyword argument
'November 12 2016'

>>> "{:%B %d %Y}".format(datetime.now())  # positional argument
'November 12 2016'
>>> "{0:%B %d %Y}".format(datetime.now())  # positional argument + explicit 0 (first arg)
'November 12 2016'

as furas commented above, this works: 正如上面的Furas所评论的,这有效:

>>> from datetime import datetime
>>> sentence = datetime.now().strftime("%B %d %Y")
>>> print sentence
November 12 2016
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM