datetime オブジェクトを印刷用の文字列形式として表示するには?
印刷しようとしている文字列は次のとおりです。
'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()
文字列の書式設定操作 ( %
) は、文字列を書式設定する 1 つの方法ですが、文字列を書式設定する別の (推奨される) 方法もあります:.format()
メソッド。
その理由は別のトピック.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'))
"Text {}, on date: {}".format(x.name, x.time)
If you are using Python 2.6 or above, then format()
is the best bet to format your string. It helps you from getting mangled with %
format specifier, with which you have to do much more task to format your string in correct format.. Else you can get TypeError