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.

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.

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

Example 1: 

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

Convert this datetime object to string in format ‘DD-MMM-YYYY (HH:MM:SS:MICROS)’ i.e.

Output:

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

Output:

Example 3: Convert Date part to String

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

Output:

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

Output:

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,

Output:

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.