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)
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)
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)
That’s all about converting String to datetime in python.
Join Our News Letter – Stay Updated
Subscribe to Awesome Java Content.