Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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" 
like image 388
TIMEX Avatar asked Jan 28 '10 22:01

TIMEX


People also ask

How do I convert a datetime to a string in Python?

To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.

How do I convert datetime to date format?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.


2 Answers

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

  • Python 2: strftime() Behavior
  • Python 3: strftime() Behavior

For this specific example, it would look something like:

my_datetime.strftime("%B %d, %Y") 
like image 116
Cristian Avatar answered Sep 30 '22 23:09

Cristian


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

like image 40
Autodidact Avatar answered Sep 30 '22 22:09

Autodidact