Python datetime to string

In this Python datetime tutorial, you will learn how to convert Python datetime to string.

# import datetime module
import datetime

# create a datetime object
var_date = datetime.datetime(2020, 4, 21)

# print the var_date
print("var_date =", var_date)

# print the type of var_date
print("type of var_date =", type(var_date))

# convert datetime to string
var_str = var_date.strftime("%d %B, %Y")

# print the var_str
print("var_str =", var_str)

# print the type of var_str
print("type of var_str =", type(var_str))

Output:

var_date = 2020-04-21 00:00:00
type of var_date = <class 'datetime.datetime'>
var_str = 21 April, 2020
type of var_str = <class 'str'>

Free resources to learn advanced skills: AiHints and CodeAllow