How to Convert String to Datetime in Python

Introduction

Python has a built-in datetime module that provides classes for manipulating dates and times.

The datetime class represents a single point in time and can be created by providing the year, month, and day as integers.

The datetime module includes a time class, a simpler version of the datetime class, and only contains information about the time, not the date.

How to convert string to datetime in Python

There is a built-in function called strptime() to convert a string to datetime in Python. The strptime() method takes an argument where you may provide date_string and format and returns the string representation of the​ date/time to a datetime object.

Syntax

datetime.strptime(date_string, format)

Parameters

The strptime() function takes both mandatory arguments and should be a string.

The strptime() function is exactly the opposite of the strftime() function, which converts a datetime object to a string.

Code example of using the strptime() method to convert the string to a datetime object

# app.py

from datetime import datetime

dt_str = '27/10/20 05:23:20'

dt_obj = datetime.strptime(dt_str, '%d/%m/%y %H:%M:%S')

print("The type of the date is now",  type(dt_obj))
print("The date is", dt_obj)

Output

The type of the date is now <class 'datetime.datetime'>
The date is 2020-10-27 05:23:20

The datetime.strptime() is a general method for parsing strings into datetimes. It can handle all sorts of formats, with the format defined by the format string you give.

Converting string to datetime using dateutil

The dateutil library provides a parser that can be used to convert strings to datetime objects. The dateutil.parser.parse() function takes a string representing a date and/or time and returns a datetime object.

The dateutil can be installed from PyPI using the pip package manager.

Import the dateutil package and use the parser module to convert the string to datetime.

# app.py

from dateutil import parser

dt_str = '27/10/20 05:23:20'

dt_obj = parser.parse(dt_str)

print("The type of the date is now",  type(dt_obj))
print("The date is", dt_obj)

Output

The type of the date is now <class 'datetime.datetime'>
The date is 2020-10-27 05:23:20

Converting a String to various datetime objects

Converting a String to datetime.datetime() Object

Use the datetime.strptime() method to convert a string to datetime.datetime() object in Python.

from datetime import datetime

date_string = "2023-01-20 19:27:56"
datetime_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(datetime_object)

Output

2023-01-20 19:27:56

The datetime.strptime() function converts a string to a datetime object.

The second parameter passed to the strptime() method is a format string defining the expected input string’s format.

In our example, the format string is “%Y-%m-%d %H:%M:%S”, which corresponds to the format of the date_string variable.

Converting a String to datetime.date() Object

To convert a string to datetime.date() object, use the datetime.strptime() method and apply the .date() function on a result of the .strptime() function.

from datetime import datetime

date_string = "2023-01-20"
date_object = datetime.strptime(date_string, "%Y-%m-%d").date()
print(date_object)

Output

2023-01-20

The datetime.strptime() function converts this string to a datetime object.

The date() method extracts the date from the datetime object.

Converting a String to datetime.time() Object

To convert a string to datetime.time() object, use the datetime.strptime() method and apply the .time() function on a result of the .strptime() function.

from datetime import datetime

time_string = "19:39:50"
time_object = datetime.strptime(time_string, "%H:%M:%S").time()
print(time_object)

Output

19:39:50

The datetime.strptime() function converts the string to a datetime object.

The time() method extracts the time from the datetime object.

Converting String to datetime.datetime() Object with Locale

To set a locale in Python, import the locale package in your program and then use the locale.setlocale() method to set the locale.

# app.py

import locale
from datetime import datetime

locale.setlocale(locale.LC_ALL, 'es_ES')
date_str_es = '27-Octubre-2020'  # es_ES locale
datetime_object = datetime.strptime(date_str_es, '%d-%B-%Y')
print(datetime_object)

Output

2020-10-27 00:00:00

FAQ

What is the difference between datetime.datetime, datetime.date and datetime.time objects?

The main difference between datetime.datetime, datetime.date, and datetime.time objects are the datetime.datetime object represents a specific time point, including the date and time while the datetime.date object represents a particular date without the time and the datetime.time object represents a particular time without a date.

What is the dateutil library, and how can it be used to convert strings to datetime objects?

The dateutil library is a third-party library for parsing and manipulating dates and times in Python that provides a parser.parse() function that can be used to convert strings to datetime objects.

What should I do if the strptime() method raises a ValueError exception when trying to convert a string to a datetime object?

If the input string is not in the expected format, the interpreter will raise a ValueError exception.

To handle the ValueError before it occurs, check the format of the input string and the format string passed to the strptime() method and make sure they match.

Conclusion

Using the strptime() function, you can convert a string to datetime in Python. This method takes an input string and format as arguments, and returns the string representation of the​ date/time to a datetime object.

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.