What is the date.strftime() method in Python?

The strftime() method converts date, time, or the datetime object to its equivalent date or time string.

An explicit format string controls the returned string formatting. Some useful directives are listed below. The complete list of argument string formatting directives is here.

Some useful directives

Directive

Meaning

%d

Day of month as zero padded decimal value.

%m

Month as zero padded decimal value.

%B

Full name of month.

%Y

Year with century as a decimal value.

%y

Year as zero padded decimal value.

%%

Literal for % symbol.

Syntax


date.strftime(format)

Parameters

  • format: This is a string format.

Return value

It returns a string representing date and time object.

Explanation

The code below demonstrates this method’s use in a program:

# Importing date class from datetime module
from datetime import date
# today's date
now = date.today()
print(now)
# Getting day of month as zero padded decimal
day = now.strftime("%d")
print("day:", day)
# Getting month as zero padded decimal value
month = now.strftime("%m")
print("month:", month)
# Getting year with century
year = now.strftime("%Y")
print("year:", year)

Code explanation

  • Line 2: We load the date class from the datetime module.

  • Line 4: We fetch today’s date using the date.today() method in the now variable.

  • Line 7: We extract the day from the now object using the %d string directive.

  • Line 10: We extract the month from the now date object using the %m string directive.

  • Line 13: We extract the year from the now date object using the %Y string directive.

Free Resources