DEV Community

Mr #1738
Mr #1738

Posted on

Converting Strings into datetime Objects in Python

If you have a string of date information, such as '2023/10/31 09:55:00'or 'October 31, 2023', and need to convert it to a datetime object, use the datetime.datetime.strptime() function. The strptime() function is the inverse of the strftime() method. A custom format string using the same directives as strftime() must be passed so that strptime() knows how to parse and understand the string. (The p in the name of the strptime() function stands for parse.)
Enter the following into interactive shell to excute:

>>> import datetime
>>> dt =datetime.datetime.now()
>>> import datetime
>>> datetime.datetime.strptime('October 31, 2023', '%B %d, %Y')
datetime.datetime(2023, 10, 31, 0, 0)
>>> datetime.datetime.strptime('2023/10/31 09:55:00', '%Y/%m/%d %H:%M:%S')
datetime.datetime(2023, 10, 31, 9, 55)
>>> datetime.datetime.strptime("October of '15",  "%B of '%y")
datetime.datetime(2015, 10, 1, 0, 0)
>>> datetime.datetime.strptime("October of '31",  "%B of '%y")
>>> datetime.datetime.strptime("November of '63", "%B of '%y")
datetime.datetime(2063, 11, 1, 0,0)
Enter fullscreen mode Exit fullscreen mode

To get a datetime object from the string 'October 31, 2023', pass 'October 31, 2023' as the first argument to strptime() and the custom format string that corresponds to 'October 31, 2023' as the second argument. The string with the date information must match the custom format string exactly, or Python will raise a ValueError exception

Top comments (2)

Collapse
 
flowzai profile image
Flowzai

Thank you so much.

Collapse
 
vincenttommi profile image
Mr #1738

welcome.