Write a Python program to convert a string into datetime


This program demonstrates how to use the strptime() method from the datetime module to convert a date string into a datetime object. The program first imports the datetime module, which provides classes for working with dates and times

Then, the strptime() method is used to convert a date string into a datetime object. The strptime() method takes two arguments - the first argument is the date string to be converted, and the second argument is a string that specifies the format of the date string.

In this program, the date string "June 8 2014 10:30:54 AM" is converted into a datetime object by specifying the format of the date string as "%B %d %Y %I:%M:%S %p", which means:

  • %B is the full name of the month
  • %d is the day of the month (01 to 31)
  • %Y is the year (four digits)
  • %I is the hour in 12-hour format (01 to 12)
  • %M is the minute (00 to 59)
  • %S is the second (00 to 59)
  • %p is the AM/PM designation

The resulting datetime object is then printed to the console.

Source Code

from datetime import datetime
 
d = datetime.strptime("June 8 2014  10:30:54 AM", "%B %d %Y %I:%M:%S %p")
print(d)

Output

2014-06-08 10:30:54

Example Programs