Python String to datetime

In this tutorial, we will see how to convert String to datetime object.
Let’s say, you got String as input and you want to convert it datetime object to extract various details from it.

  • Using strptime
  • Using parser

Using strptime method

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

Output:

datetime Obj: 2019-04-15 20:29:00

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

  • %b Month as locale’s abbreviated name(Apr)
  • %d Day of the month as a zero-padded decimal number(15)
  • %Y Year with century as a decimal number(2019)
  • %I Hour (12-hour clock) as a zero-padded decimal number(8)
  • %M Minute as a zero-padded decimal number(29)
  • %p Locale’s equivalent of either AM or PM(PM)

Using parser

You can use third party module dateUtil to get object of datetime object.

Output:

datetime Obj: 2019-04-15 20:29:00

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

Was this post helpful?

Leave a Reply

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