In this Python article, we will discuss the use of strptime function, and how to use this to convert string to a datetime object. We will also discuss various examples to understand the concept better. Let’s get started.
Table of Contents
1. What is the use of datetime strptime in Python?
We use the function or method strptime() to convert a provided string into a DateTime object. The condition is that the string should be a valid representation of datetime.
The datetime.strptime() function intakes a time signifying string in different formats; a struct_time is returned in either gmtime() format or localtime() format.
The strptime takes the parameter similar to directives used by strftime function. The default format is “%a %b %d %H:%M:%S %Y”, its formatting is the same that is returned by ctime().
When the provided string format is invalid or when the parsed value has too much data then ValueError is thrown.
Traceback (most recent call last):
File "main.py", line 4, in
f1 = datetime.datetime.strptime(string, '%H::%M::%S').time()
File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
ValueError: time data '12::two minutes::39' does not match format '%H::%M::%S'
We can remove such errors using exception handling by catching the exception and correcting it.
Let’s do it on one other example. Try the above yourself after watching one.
Error Raised: time data '07/2021/05 12:45:49' does not match format '%m/%d/%y'
Error Raised: time data '99::55::26' does not match format '%H::%M::%S'
Finally, if we sum up, in this article we learned everything about the strptime function/method. We covered how to use and why to use the strptime function for milliseconds and different input formats, we also covered:
What is the use of Strptime in python and how to use the strptime in python
Different format Code List for the strptime function/method
ValueError in strptime() and how to remove the valueerror in strptime() fucntion