How to Convert Date to String in Python

Itacen Sabacok | Sep 30, 2022

The strftime() method returns a string representing date and time using date, time or datetime object.

 1from datetime import datetime
 2
 3now = datetime.now() # now is a datetime object
 4
 5year = now.strftime("%Y")
 6print("year:", year)
 7
 8month = now.strftime("%m")
 9print("month:", month)
10
11date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
12print("datetime:",date_time)

OUTPUT:

year: 2022

month: 10

datetime: 02/05/2022, 16:25:19