Algorithm
-
Import Module:
- Import the
datetime
module.
- Import the
-
Get Input:
- Receive the date string as input.
-
Specify Format:
- Define the expected format of the date string.
-
Convert to Datetime:
- Use
datetime.strptime()
to convert the string to a datetime object based on the specified format.
- Use
-
Handle Errors:
- Catch any
ValueError
exceptions that may arise during the conversion.
- Catch any
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
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
2011-03-11 11:31:00
Demonstration
Python Programing Example to Convert String to Datetime-DevsEnv