Converting string to datetime object in Python

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")
Converting string to datetime object in Python

Read my other article about converting date string of mm/dd/yyyy or dd/mm/yyyy format to date object.

Reference

Related Articles & Tools

Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.