How to display a datetime object as a string format for printing?
Here is the string I am trying to print:
'Text %s, on date: %d' % (x.name, x.time)
And here is the error I am getting:
%d format: a number is required, not datetime.datetime
How to display a datetime object as a string format for printing?
Here is the string I am trying to print:
'Text %s, on date: %d' % (x.name, x.time)
And here is the error I am getting:
%d format: a number is required, not datetime.datetime
You need to change the type: in template or in argument:
'Text %s, on date: %s' % (x.name, x.time)
But datetime.datetime
instance is just an object (it has some kind-of-human-friendly string representation). You can change that to be friendlier this way:
'Text %s, on date: %s' % (x.name, x.time.isoformat())
You can even format it using strftime()
:
'Text %s, on date: %s' % (x.name, x.time.strftime('%A, %B %d, %Y'))
Lets test it:
>>> 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()
String formatting operations (%
) are one way of formatting string, but there is also another - preferred - way to format strings: .format()
method.
The reason for that is a different topic, but I can show you how the above examples would look like using .format()
method:
'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