One common requirement in programming is to convert date and time in string format to a datetime object. Here we will see simple tip to cinvert a string to datetime object in Python programming using the datetime.strptime() method.
Let us see how to convert a date string of “Sep 16 2003 11:42AM” or “Nov 2 1923 1:00PM” format to datetime.
from datetime import datetime
# Date and time in string format
dateStr = "Sep 16 2003 11:42AM"
# convert to datetime object
dateTimeObj = datetime.strptime(dateStr, '%b %d %Y %I:%M%p')
print("\n Date & Time: ", dateTimeObj, "\n")
print("\n Type: ", type(dateTimeObj), "\n")
Read my other article about converting date string of mm/dd/yyyy or dd/mm/yyyy format to date object.
Reference
- More about datetime.strptime() as Python Docs.