What is a strptime in Python?
strptime() function is used to convert a given string into datetime.
This function is available in dateTime and time modules to parse a string to datetime ans time modules to parse a string to datetime and time objects respectively.
In this tutorial, we will see specific examples of strptime( function to convert string to DateTime and time objects.
Syntax:-
datetime.strptime(date_string, format) date_string → is the time present in string format. format →Where format is the desired format of the date string that user wants. Format is built using codes shown in the below image
Example 1: string to datetime object
Python Code
from datetime import datetime
input_string = "MAY 22, 2020"
print("type of input_string =", type(input_string))
print("given_input_string =", input_string)
datetime = datetime.strptime(input_string, "%B %d, %Y")
print("type of input_string =", type(datetime))
print("datetime =", datetime)
Output:
type of input_string = <class ‘str’>
given_input_string = MAY 22, 2020
type of input_string = <class ‘datetime.datetime’>
datetime = 2020-05-22 00:00:00
Example 2 :- date is in dd/mm/yyyy format
Code:
Python Code
from datetime import datetime
input_string = "12/11/2018 09:15:32"
datetime = datetime.strptime(input_string, "%d/%m/%Y %H:%M:%S")
print("datetime =", datetime)
Output:
datetime = 2018-11-12 09:15:32
Example 3:- date is in mm/dd/yyyy format
Code:
Python Code
from datetime import datetime
input_string = "04/05/2003 10:36:21"
datetime = datetime.strptime(input_string, "%m/%d/%Y %H:%M:%S")
print("datetime =", datetime)
Output:
datetime = 2003-04-05 10:36:21
ValueError in strptime()
Code:
Python Code
from datetime import datetime
input_string = "11/MAY/2022"
datetime = datetime.strptime(input_string, "%m %d %Y")
print("datetime =", datetime)
Output:
raise ValueError(“time data %r does not match format %r” %
ValueError: time data ’11/MAY/2022′ does not match format ‘%m %d %Y’
Special thanks to JAIGANESH R S for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article. If you want to suggest any improvement/correction in this article please mail us at [email protected]