22
Python string to datetime Conversion
ItsMyCode |
There are several ways to convert string to datetime in Python. Let’s take a look at each of these with examples.
We can convert a string to datetime using the 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.
Syntax
**datetime.strptime(date\_string, format)**
Parameters
The strptime()
class method takes two arguments:
- date_string (that be converted to datetime)
- format code
Let’s take a few examples to demonstrate the 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)
Output
The type of the date is now <class 'datetime.datetime'>
The date is 2021-11-22 03:15:10
If you want to convert the string into date format, we can use the 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)
Output
The type of the date is now <class 'datetime.date'>
The date is 2021-11-22
If you want to convert the string into date format, we can use the 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)
Output
The type of the date is now <class 'datetime.time'>
The date is 03:15:10
The other way to convert string to datetime is using the dateutil module. The only parameter it takes is the string object and converts it into a datetime object.
Example
# 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)
Output
The type of the date is now <class 'datetime.datetime'>
The date is 2021-11-22 03:15:10
The post Python string to datetime Conversion appeared first on ItsMyCode.
22