Python datetime to String

Previous
Next

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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog