Python : How to convert datetime object to string using datetime.strftime()

How to convert datetime object to string using datetime.strftime() function in python ?

In this article we’ll discuss how to convert datetime object to string using datetime.strtime() function.

Strptime() :

In Python, the time method strptime() generally parses a string which represents a time according to a format. The return value is a struct_time as returned by localtime().

Python strtime() is a class method in datetime class.

Let’s try with different examples:

#Program :

From datetime import datetime

#current date and time
now = datetime.now()
date_time = now.strftime(‘%m/%d/%Y , %H:%M:%S’)
print(‘date and time’, date_time)
Output :
date and time 04/24/2021 , 06:40:15

Here, ‘date_time’  is the string  and ‘now’ is a ‘datetime’ object.

Local’s appropriate date and time :

#Program

from datetime import datetime

timestamp = 1528797322
date_time = datetime.fromtimestamp(timestamp)

#Converting Date part to String
d = date_time.strftime(‘%c’)
print(‘1st output’, d)

#Converting Date part to String
d = date_time.strftime(‘%x’)
print(‘2nd output’, d)

#Converting datetime to text
d = date_time.strftime(‘%X’)
print(‘3rd output’, d)
Output :
date and time 04/24/2021 , 06:40:15
1st output: Sat Jan 12 09:55:22 2018
2nd output: 01/12/18
3rd output: 09:55:22

Here, format codes %c, %x, and  %X are used for local’s appropriate date and time representation.