Python String to datetime

Previous
Next

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.

from datetime import datetime datetime_object = datetime.strptime('Apr 15 2019 8:29PM', '%b %d %Y %I:%M%p') print("datetime Obj:",datetime_object)

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.

from dateutil import parser dt = parser.parse("Apr 15 2019 8:29PM") print("datetime Obj:",dt)

Output:

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

That’s all about converting String to datetime 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