← Go Back
The first argument given to
How to Convert a String to a Date
Using thedatetime.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.🐍 You might also find interesting: