How to Convert a String to Date in Python?

In this tutorial, I will explain how to convert a string to date in Python. Recently someone asked me this doubt on how to convert string to date during a Python webinar. Then I explored more about this topic and I will share my findings in this article. Let us learn more about this topic today.

Date Formats

When working with dates in programming, it’s crucial to recognize the format in which dates are represented. The ‘YYYY-MM-DD’ format is widely used, especially in the United States, as it aligns with ISO 8601 standards. For instance, a date like ‘2024-11-12’ corresponds to November 12, 2024. Converting this string into a date object allows for easier manipulation and comparison of dates within your Python programs.

Read How to Compare Strings in Python?

The datetime Module

Python’s built-in datetime module provides the necessary tools for working with dates and times. The strptime() method is particularly useful for converting strings into date objects. Here’s how it works:

Syntax of strptime()

from datetime import datetime

date_object = datetime.strptime(date_string, format)
  • date_string: The string representing the date (e.g., ‘2024-11-12’).
  • format: The format in which the date is represented (e.g., ‘%Y-%m-%d’).

Read How to Create a String of N Characters in Python?

Example: Convert a String to Date

Let’s consider a practical example involving a fictional character, John Smith, who has a birthday stored as a string.

Step 1: Import the datetime Module

First, you need to import the datetime class from the datetime module.

from datetime import datetime

Step 2: Define the Date String

Next, define the date string you want to convert.

date_string = '1985-07-23'  # John's birthday in YYYY-MM-DD format

Read How to Split a String into Equal Parts in Python?

Step 3: Convert the String to a Date Object

Now, use the strptime() method to convert the string into a date object.

date_format = '%Y-%m-%d'
johns_birthday = datetime.strptime(date_string, date_format)

Step 4: Verify the Conversion

You can print the date object to verify the conversion.

print("John's birthday is:", johns_birthday)

Output:

John's birthday is: 1985-07-23 00:00:00

I have executed the above example code and added the screenshot below.

Convert a String to Date in Python

The output shows that the string has been successfully converted into a date object, which includes a time component (defaulting to midnight).

Read How to Insert a Python Variable into a String?

Handle Invalid Date Strings

When converting strings to date objects, it’s important to handle potential errors, such as invalid date formats. You can use a try-except block to catch exceptions.

try:
    invalid_date_string = '2024-02-30'  # Invalid date (February 30 does not exist)
    invalid_date = datetime.strptime(invalid_date_string, date_format)
except ValueError as e:
    print("Error:", e)

Output:

Error: day is out of range for month

I have executed the above example code and added the screenshot below.

How to Convert a String to Date in Python

This output indicates that the provided date string is invalid, allowing you to handle such cases gracefully in your application.

Read How to Split a String by Index in Python?

Conclusion

In this tutorial, I have explained how to convert a string to date in Python. We learned using the datetime module’s strptime() method. This technique is essential for data validation, manipulation, and comparison in any Python application dealing with dates.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.