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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Solution
You need to change the type: in template or in argument:
But
datetime.datetimeinstance is just an object (it has some kind-of-human-friendly string representation). You can change that to be friendlier this way:You can even format it using
strftime():Test
Lets test it:
Alternative –
.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: