← Go Back

How to Convert a String to a Date

Using the datetime.datetime.strptime() standard function:

import datetime

date_str = "08/15/2022"
date = datetime.datetime.strptime(date_str, "%d/%m/%Y").date()
print(type(date)) # <class 'datetime.date'>

The first argument given to strptime() must be a string containing a date. The second indicates the date format of the string. The %d format code represents a number between 01 and 31, %m is the month number between 01 and 12, and %Y is the year between 0001 and 9999. The %d/%m/%Y format (i.e., dd/mm/yyyy) is the most common for representing dates as strings. For other available format codes see the official documentation.

strings dates datetime conversion

🐍 You might also find interesting: