¿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"
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")
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...
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.
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.
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}'
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'
>>>
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)
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