How do you convert string to a strongly-typed datetime in Python?

Experience Level: Junior
Tags: Python

Answer

To convert a string to strongly-typed datetime, import the datetime module. Then call strptime() function with the format that defines how the parsing will be done.

Hint: strptime stands for string parse time.

Example:

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
Python for beginners
Python for beginners

Are you learning Python ? Try our test we designed to help you progress faster.

Test yourself