How do I turn a python datetime into a string, with readable format date?

Viewed 368039
t = e['updated_parsed']
dt = datetime.datetime(t[0],t[1],t[2],t[3],t[4],t[5],t[6]
print dt
>>>2010-01-28 08:39:49.000003

How do I turn that into a string?:

"January 28, 2010"
8 Answers

The datetime class has a method strftime. The Python docs documents the different formats it accepts:

For this specific example, it would look something like:

my_datetime.strftime("%B %d, %Y")

Using f-strings, in Python 3.6+.

from datetime import datetime

date_string = f'{datetime.now():%Y-%m-%d %H:%M:%S%z}'

Python datetime object has a method attribute, which prints in readable format.

>>> a = datetime.now()
>>> a.ctime()
'Mon May 21 18:35:18 2018'
>>> 

For those who are impatient to read the nice official docs strftime :)

from datetime import datetime
datetime.now().strftime("%H:%M %B %d, %Y")
'12:11 August 08, 2022'
Related