In this article, we are going to learn how we can convert from string to a given date time in Python. We will make use of the datetime module of Python. We will take input from the user in a given date-time formatted string. Once we have this date time string then we will convert it to a date and time object of Python.
Environment and requirements-
Python interpreter
datetime library
Python Program to convert string to datetime
- First, we import datetime class from datetime module.
- Get input from the user in a specified format.
- We use datetime.strptime() method.
- Print the output of the code.
from datetime import datetime
print("Please Enter the date time string in MMDDYYHHMMSS format: ")
datetime_str=input()
format = '%m/%d/%y %H:%M:%S'
datetime_object = datetime.strptime(datetime_str, format)
print(type(datetime_object))
print(datetime_object)
Output-