Table of Contents
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.
1 2 3 4 5 6 |
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.
1 2 3 4 5 |
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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.