Advertisement
Advertisement


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


Question

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"
2010/01/28
1
172
1/28/2010 10:20:05 PM

Accepted Answer

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")
2019/02/05
244
2/5/2019 5:28:33 PM


Using f-strings, in Python 3.6+.

from datetime import datetime

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

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.

2017/07/22

Read strfrtime from the official docs.

2017/09/18

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

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

This is for format the date?

def format_date(day, month, year):
        # {} betekent 'plaats hier stringvoorstelling van volgend argument'
        return "{}/{}/{}".format(day, month, year)
2017/04/07

Source: https://stackoverflow.com/questions/2158347
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]