In this article we will discuss how to convert a datetime class object to different string formats using datetime.strftime() function.

datetime.strftime()

Python’s datetime class provides a member function strftime() to create string representation of data in the object i.e.

datetime.strftime(Format_String)

It accepts a format string as argument and converts the data in object to string according to format codes in given format string.

To use this we need to import datetime class from python’s datetime module i.e.

from datetime import datetime

Let’s use it to convert datetime object to string.

Example 1: 

Get the current timestamp in a datetime object i.e.

dateTimeObj = datetime.now()

Convert this datetime object to string in format ‘DD-MMM-YYYY (HH:MM:SS:MICROS)’ i.e.
timestampStr = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S.%f)")

print('Current Timestamp : ', timestampStr)

Output:
Current Timestamp :  18-Nov-2018 (08:34:58.674035)

Format string used here is “%d-%b-%Y (%H:%M:%S.%f)“. The format string contains the codes pointing to each element of datetime like %d for day of month & %Y for year etc.

Complete list of format code :

Format Codes Description Example
%d Day of the month as a zero-padded decimal number 01, 02, 03, 04 …, 31
%a Weekday as abbreviated name Sun, Mon, …, Sat
%A Weekday as full name Sunday, Monday, …, Saturday
%m Month as a zero-padded decimal number 01, 02, 03, 04 …, 12
%b Month as abbreviated name Jan, Feb, …, Dec
%B Month as full name January, February, …, December
%y Year without century as a zero-padded decimal number 00, 01, …, 99
%Y Year with century as a decimal number 0001, …, 2018, …, 9999
%H Hour (24-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 23
%M Minute as a zero-padded decimal number 01, 02, 03, 04 …, 59
%S Second as a zero-padded decimal number 01, 02, 03, 04 …, 59
%f Microsecond as a decimal number, zero-padded on the left 000000, 000001, …, 999999
%I Hour (12-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 12
%p Locale’s equivalent of either AM or PM AM , PM
%j Day of the year as a zero-padded decimal number 01, 02, 03, 04 …, 366

Let’s see some other examples,

Example 2:

Convert datetime object to string in format HH:MM:SS.MICROS – MMM DD YYYY

dateTimeObj = datetime.now()

timestampStr = dateTimeObj.strftime("%H:%M:%S.%f - %b %d %Y")

print('Current Timestamp : ', timestampStr)

Output:
Current Timestamp :  08:34:58.674035 - Nov 18 2018

Example 3: Convert Date part to String

Convert the date part only from datetime object to string in format DD MMM YYYY

dateStr = dateTimeObj.strftime("%d %b %Y ")

print('Current Date : ' ,dateStr)

Output:
Current Date :  18 Nov 2018

Example 4: Convert Time part to string

Similarly we can convert time part only from datetime object to string i.e. in format HH:MM:SS.MICROS

timeStr = dateTimeObj.strftime("%H:%M:%S.%f")

print('Current Timestamp : ', timeStr)

Output:
Current Timestamp :  08:34:58.674035

Example 4 : Converting datetime to text

Some we need to convert datetime object to more readable text. For example let’s see how to convert a datetime object to a text format like this,

November the 17 of 2018 the Saturday at 05:10 PM

Let’s see how to do that,

dateStr = dateTimeObj.strftime("%B the %d of %Y is %A at %I:%M %p")

print(dateStr)

Output:
November the 18 of 2018 is Sunday at 08:34 AM

Complete example is as follows,
from datetime import datetime

def main():

   # Get datetime object representing the current local date and time
   dateTimeObj = datetime.now()

   print("*** Converting datetime object to string in format 'DD-MMM-YYYY (HH:MM:SS:MICROS)' ***")
   timestampStr = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S.%f)")
   print('Current Timestamp : ', timestampStr)

   print("*** Converting datetime object to string in format HH:MM:SS.MICROS - MMM DD YYYY ***")
   timestampStr = dateTimeObj.strftime("%H:%M:%S.%f - %b %d %Y")
   print('Current Timestamp : ', timestampStr)

   print('*** Create date part from datetime object to string ***')

   dateStr = dateTimeObj.strftime("%d %b %Y ")
   print('Current Date : ' ,dateStr)

   print('*** Create time part from datetime object to string ***')
   timeStr = dateTimeObj.strftime("%H:%M:%S.%f")
   print('Current Timestamp : ', timeStr)

   print("*** Converting datetime object to text format ***")
   dateStr = dateTimeObj.strftime("%B the %d of %Y is %A at %I:%M %p")
   print(dateStr)


if __name__ == '__main__':
   main()


Output:
*** Converting datetime object to string in format 'DD-MMM-YYYY (HH:MM:SS:MICROS)' ***
Current Timestamp :  18-Nov-2018 (09:06:58.492717)
*** Converting datetime object to string in format HH:MM:SS.MICROS - MMM DD YYYY ***
Current Timestamp :  09:06:58.492717 - Nov 18 2018
*** Create date part from datetime object to string ***
Current Date :  18 Nov 2018 
*** Create time part from datetime object to string ***
Current Timestamp :  09:06:58.492717
*** Converting datetime object to text format ***
November the 18 of 2018 is Sunday at 09:06 AM

 

Join a list of 2000+ Programmers for latest Tips & Tutorials