25
loading...
This website collects cookies to deliver better user experience
strptime()
function. The strptime()
function is available in Python’s datetime and time module and can be used to parse a string to datetime objects.**datetime.strptime(date\_string, format)**
strptime()
class method takes two arguments:strptime()
function use case.# Python program to convert string to datetime
#import datetime module
from datetime import datetime
# datetime in string variable
date_str = '22/11/21 03:15:10'
# convert string into datetime using strptime() function
date_obj = datetime.strptime(date_str, '%d/%m/%y %H:%M:%S')
print("The type of the date is now", type(date_obj))
print("The date is", date_obj)
The type of the date is now <class 'datetime.datetime'>
The date is 2021-11-22 03:15:10
date()
function and the strptime()
function, as shown in the example below.# Python program to convert string to date object
#import datetime module
from datetime import datetime
# datetime in string variable
date_str = '22/11/21 03:15:10'
# covert string into datetime using strptime() function
date_obj = datetime.strptime(date_str, '%d/%m/%y %H:%M:%S').date()
print("The type of the date is now", type(date_obj))
print("The date is", date_obj)
The type of the date is now <class 'datetime.date'>
The date is 2021-11-22
time()
function and the strptime()
function, as shown in the example below.# Python program to convert string to datetime
#import datetime module
from datetime import datetime
# datetime in string variable
date_str = '22/11/21 03:15:10'
# covert string into datetime using strptime() function
date_obj = datetime.strptime(date_str, '%d/%m/%y %H:%M:%S').time()
print("The type of the date is now", type(date_obj))
print("The date is", date_obj)
The type of the date is now <class 'datetime.time'>
The date is 03:15:10
# Python program to convert string to datetime
#import dateutil module
from dateutil import parser
# datetime in string variable
date_str = '22/11/21 03:15:10'
# covert string into datetime using parse() function
date_obj = parser.parse(date_str)
print("The type of the date is now", type(date_obj))
print("The date is", date_obj)
The type of the date is now <class 'datetime.datetime'>
The date is 2021-11-22 03:15:10