In this post, we will learn about strftime() method from Python datetime package.

The strftime converts date object to a string date.

Python Strftime Format

The syntax  of  strftime() method is...

dateobject.strftime(format)

Where format is the desired format of date string that user wants. Format is built using codes shown in the table below...

Code Meaning
%a Weekday as Sun, Mon
%A Weekday as full name as Sunday, Monday
%w Weekday as decimal no as 0,1,2...
%d Day of month as 01,02
%b Months as Jan, Feb
%B Months as January, February
%m Months as 01,02
%y Year without century as 11,12,13
%Y Year with century 2011,2012
%H 24 Hours clock from 00 to 23
%I 12 Hours clock from 01 to 12
%p AM, PM
%M Minutes from 00 to 59
%S Seconds from 00 to 59
%f Microseconds 6 decimal numbers

Datetime To String Python

Example: Convert current time to date string...

import datetime 
from datetime import datetime
now = datetime.now()
print(now)
datetime.datetime(2020, 9, 22, 3, 20, 22, 255262)

Let us convert the above datetime object to datetime string now.

now.strftime("%Y-%m-%d %H:%M:%S")

The output of above command will be...

'2020-09-22 03:20:22'

If you want to print month as locale’s abbreviated name, replace %m with %b as shown below...

now.strftime("%Y-%b-%d %H:%M:%S")

You should see this ...

'2020-Sep-22 03:20:22'

Another example...

now.strftime("%Y/%b/%A %H:%M:%S")
'2020-Sep-Tuesday 03:20:22'

If you just want to extract the date and ignore time, then do following...

now.strftime("%Y-%m-%d)

Output of above should be...

'2020-09-22'

Date To String Python

Date to string is quite similar to datetime to string Python conversion.

Example: Convert current date object to Python date string.

today = datetime.today()
print(today)
 datetime.datetime(2020, 9, 22, 3, 50, 1, 268575)

Let us convert the above date object to Python date string using strftime().

today.strftime("%Y-%m-%d %H:%M:%S")

output of above command...

'2020-09-22 03:50:01'

Python Strftime Milliseconds

To get a date string with milliseconds, use %f format code at the end as shown below..

today = datetime.today()
today.strftime("%Y-%m-%d %H:%M:%S.%f")

You should see following output...

'2020-09-22 03:50:01.268575'