Convert string to datetime and datetime to string in Python

The following code shows how to convert datetime of string type to datetime in Python:


from datetime import datetime

str_date = "2021-03-11 16:00:13"
my_date = datetime.strptime(str_date, "%Y-%m-%d %H:%M:%S")
print(my_date)
print(type(my_date))
Output:
2021-03-11 16:00:13
<class 'datetime.datetime'>

The following code shows how to convert datetime to string in Python:


from datetime import datetime

current_datetime = datetime.now()
str_date = datetime.strftime(current_datetime, "%Y-%m-%d %H:%M:%S")
print(str_date)
print(type(str_date))
Output:
2021-05-28 15:16:11
<class 'str'>