How do I turn a python datetime into a string, with readable format date?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping
--
Chapters
00:00 How Do I Turn A Python Datetime Into A String, With Readable Format Date?
00:19 Accepted Answer Score 305
00:41 Answer 2 Score 128
01:35 Answer 3 Score 89
01:54 Answer 4 Score 35
02:28 Answer 5 Score 19
02:43 Thank you
--
Full question
https://stackoverflow.com/questions/2158...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datetime #stringformatting
#avk47
ACCEPTED ANSWER
Score 316
The datetime class has a method strftime. The Python docs documents the different formats it accepts: strftime() and strptime() Behavior
For this specific example, it would look something like:
my_datetime.strftime("%B %d, %Y")
ANSWER 2
Score 131
Here is how you can accomplish the same using python's general formatting function...
>>>from datetime import datetime
>>>"{:%B %d, %Y}".format(datetime.now())
The formatting characters used here are the same as those used by strftime. Don't miss the leading : in the format specifier.
Using format() instead of strftime() in most cases can make the code more readable, easier to write and consistent with the way formatted output is generated...
>>>"{} today's date is: {:%B %d, %Y}".format("Andre", datetime.now())
Compare the above with the following strftime() alternative...
>>>"{} today's date is {}".format("Andre", datetime.now().strftime("%B %d, %Y"))
Moreover, the following is not going to work...
>>>datetime.now().strftime("%s %B %d, %Y" % "Andre")
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
datetime.now().strftime("%s %B %d, %Y" % "Andre")
TypeError: not enough arguments for format string
And so on...
ANSWER 3
Score 37
very old question, i know. but with the new f-strings (starting from python 3.6) there are fresh options. so here for completeness:
from datetime import datetime
dt = datetime.now()
# str.format
strg = '{:%B %d, %Y}'.format(dt)
print(strg) # July 22, 2017
# datetime.strftime
strg = dt.strftime('%B %d, %Y')
print(strg) # July 22, 2017
# f-strings in python >= 3.6
strg = f'{dt:%B %d, %Y}'
print(strg) # July 22, 2017
strftime() and strptime() Behavior explains what the format specifiers mean.
ANSWER 4
Score 19
Python datetime object has a method attribute, which prints in readable format.
>>> a = datetime.now()
>>> a.ctime()
'Mon May 21 18:35:18 2018'
>>>