2 ways to convert a string to a datetime object in Python:
- Using datetime module
- Using dateutil module
Method 1: Using datetime module
The strptime() function from the datetime module parses the string according to the provided format and converts it into a datetime object.
Visual Representation
Example
from datetime import datetime
# string representing a date and time
date_string = "13-08-2022 11:23:44"
print(type(date_string))
# Specify the format that matches the string
format = "%d-%m-%Y %H:%M:%S"
# Convert the string to a datetime object
datetime_object = datetime.strptime(date_string, format)
print(datetime_object)
print(type(datetime_object))
Output
<class 'str'>
2022-08-13 11:23:44
<class 'datetime.datetime'>
If the format does not match, it will raise a ValueError.
Method 2: Using dateutil module
The parser.parse() method from dateutil module provides a parser that can automatically recognize many different date formats without the need to specify the format explicitly.
It takes a string representing a date and time and returns a datetime object.
Visual Representation
Example
from dateutil import parser
# Define a string representing a date and time
date_string = "13-08-2022 11:23:44"
print(type(date_string))
#using dateutil's parser
datetime_object = parser.parse(date_string)
print(datetime_object)
print(type(datetime_object))
Output
<class 'str'>
2022-08-13 11:23:44
<class 'datetime.datetime'>
Related posts
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.