How to Convert a String to a DateTime in Python

2 ways to convert a string to a datetime object in Python:

  1. Using datetime module
  2. 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

Visual Representation of Convert a String to a DateTime in Python Using datetime module

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

Visual Representation of Using dateutil module

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

Python datetime to string

Python Date Format

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.