Algorithm


  1. Import Module:

    • Import the datetime module.
  2. Get Input:

    • Receive the date string as input.
  3. Specify Format:

    • Define the expected format of the date string.
  4. Convert to Datetime:

    • Use datetime.strptime() to convert the string to a datetime object based on the specified format.
  5. Handle Errors:

    • Catch any ValueError exceptions that may arise during the conversion.

 

Code Examples

#1 Code Example- Python Programing Using datetime module

Code - Python Programming

from datetime import datetime

my_date_string = "Mar 11 2011 11:31AM"

datetime_object = datetime.strptime(my_date_string, '%b %d %Y %I:%M%p')

print(type(datetime_object))
print(datetime_object)
Copy The Code & Try With Live Editor

Output

x
+
cmd

2011-03-11 11:31:00

#2 Code Example- python Programing Using dateutil module

Code - Python Programming

from dateutil import parser

date_time = parser.parse("Mar 11 2011 11:31AM")

print(date_time)
print(type(date_time))
Copy The Code & Try With Live Editor

Output

x
+
cmd
2011-03-11 11:31:00
Advertisements

Demonstration


Python Programing Example to Convert String to Datetime-DevsEnv