如何将日期时间对象显示为字符串格式以便打印?
这是我要打印的字符串:
'Text %s, on date: %d' % (x.name, x.time)
这是我得到的错误:
%d format: a number is required, not datetime.datetime
最佳答案
解决方案
您需要更改类型:在模板中或在参数中:
'Text %s, on date: %s' % (x.name, x.time)
但是 datetime.datetime
实例只是一个对象(它具有某种对人类友好的字符串表示形式)。您可以通过这种方式将其更改为更友好:
'Text %s, on date: %s' % (x.name, x.time.isoformat())
您甚至可以使用 strftime()
对其进行格式化:
'Text %s, on date: %s' % (x.name, x.time.strftime('%A, %B %d, %Y'))
测试
让我们测试一下:
>>> import datetime
>>> now = datetime.datetime.now() # our "now" timestamp
>>> '%d' % now
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
'%d' % datetime.datetime.now()
TypeError: %d format: a number is required, not datetime.datetime
>>> '%s' % now.isoformat()
'2012-09-25T22:24:30.399000'
>>> now.strftime('%A, %B %d, %Y')
'Tuesday, September 25, 2012'
备选方案 - .format()
字符串格式化操作 (%
) 是格式化字符串的一种方式,但还有另一种 - 首选 - 格式化字符串的方式:.format()
方法。
原因is a different topic , 但我可以向您展示上面的示例如何使用 .format()
方法:
'Text {x.name}, on date: {x.time}'.format(x=x) # accessing properties
'Text {0}, on date: {1}'.format(x.name, x.time) # accessing by positions
'Text {}, on date: {}'.format(x.name, x.time) # in Python >2.7 it can be shorter
'Text {0}, on date: {1}'.format(x.name, x.time.isoformat()) # ISO format
'Text {0}, on date: {1}'.format(x.name, x.time.strftime('%A, %B %d, %Y'))
关于python - printf 在 Python 中将时间格式化为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12590415/