¿Cómo convierto una datetime de python en una cadena, con fecha de formato legible?


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

¿Cómo puedo convertir eso en una cadena?:

"January 28, 2010"
Author: SilentGhost, 2010-01-29

7 answers

La clase datetime tiene un método strftime. strftime() Behavior en Python docs documenta los diferentes formatos que acepta.

Para este ejemplo específico, se vería algo como:

my_datetime.strftime("%B %d, %Y")
 193
Author: Cristian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-25 00:11:37

Aquí está cómo puede lograr lo mismo usando la función de formato general de python...

>>>from datetime import datetime
>>>"{:%B %d, %Y}".format(datetime.now())

Los caracteres de formato utilizados aquí son los mismos que los utilizados por strftime. No se pierda la : inicial en el especificador de formato.

Usar format() en lugar de strftime() en la mayoría de los casos puede hacer que el código sea más legible, más fácil de escribir y consistente con la forma en que se genera la salida formateada...

>>>"{} today's date is: {:%B %d, %Y}".format("Andre", datetime.now())

Compare lo anterior con el siguiente strftime() alternativa...

>>>"{} today's date is {}".format("Andre", datetime.now().strftime("%B %d, %Y"))

Además, lo siguiente no va a funcionar...

>>>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

Y así sucesivamente...

 88
Author: Sandeep Datta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-06 16:15:11

Pregunta muy antigua, lo sé. pero con las nuevas f-strings (a partir de python 3.6) hay nuevas opciones. así que aquí para completar:

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() ystrptime() Behavior explica lo que significan los especificadores de formato.

 9
Author: hiro protagonist,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-22 12:32:53

Lee strfrtime de los documentos oficiales.

 7
Author: S.Lott,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-18 20:12:47
from datetime import datetime

date_string = f'{datetime.now():%Y-%m-%d %H:%M:%S%z}'
 4
Author: Natim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-10 09:55:54

El objeto datetime de Python tiene un atributo method, que se imprime en formato legible.

>>> a = datetime.now()
>>> a.ctime()
'Mon May 21 18:35:18 2018'
>>> 
 1
Author: Vikram S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-21 13:07:17

Esto es para formatear la fecha?

def format_date(day, month, year):
        # {} betekent 'plaats hier stringvoorstelling van volgend argument'
        return "{}/{}/{}".format(day, month, year)
 -1
Author: Thomas Wouters,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-07 08:38:31