Python datetime to String

In this tutorial, we will see how to convert datetime to String object.
Let’s say, you have datetime as input and you want to convert it string to display it.

  • Using strftime
  • Using format

Using strptime method

You can simply use strptime to convert datetime to String.
Let’s understand with the help of example.

from datetime import datetime
t = datetime(2017, 12, 31, 0, 0)
dtStr=t.strftime('%m/%d/%Y')
print("datetime in String format:",dtStr)

Output:

datetime in String format: 12/31/2017

Let’s understand mening of %b,%d,%Y,%I,%M and %p

  • %m Month as a zero-padded decimal number(12)
  • %d Day of the month as a zero-padded decimal number(31)
  • %Y Year with century as a decimal number(2017)

Using String’s format method

You can use String’s format method to achieve same results.
Let’s understand with the help of example.

from datetime import datetime
t = datetime(2015, 11, 27, 0, 0)
dtStr='{:%m/%d/%Y}'.format(t)
print("datetime in String format:",dtStr)

Output:

datetime in String format: 11/27/2015

That’s all about converting datetime to string in python.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.