How to Convert String to Date in Python

To convert a string to a date in Python, you can use the datetime module.

The following example shows how to convert a string to a date using the datetime module in Python.

Using datetime Module

We can use the datetime module to convert a string to a date.

Suppose we have the following string:

from datetime import datetime

# Declare string
date_string = '2021-12-11'

# Convert string to datetime
date_object = datetime.strptime(date_string, "%Y-%m-%d")

# Show result
print(date_object)

Output: 👇️

2021-12-11 00:00:00

In this example, we use the datetime.strptime() function to convert the string date_string to a datetime object date_object. The output shows the datetime object created from the string using the datetime module.

Conclusion

We can use the datetime module to convert a string to a date in Python. This method provides a convenient way to handle date conversions from strings.