What is the date.strftime() method in Python?
Some useful directives
Directive | Meaning |
| Day of month as zero padded decimal value. |
| Month as zero padded decimal value. |
| Full name of month. |
| Year with century as a decimal value. |
| Year as zero padded decimal value. |
| Literal for |
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 modulefrom datetime import date# today's datenow = date.today()print(now)# Getting day of month as zero padded decimalday = now.strftime("%d")print("day:", day)# Getting month as zero padded decimal valuemonth = now.strftime("%m")print("month:", month)# Getting year with centuryyear = now.strftime("%Y")print("year:", year)
Code explanation
-
Line 2: We load the
dateclass from thedatetimemodule. -
Line 4: We fetch today’s date using the
date.today()method in thenowvariable. -
Line 7: We extract the day from the
nowobject using the%dstring directive. -
Line 10: We extract the month from the
nowdate object using the%mstring directive. -
Line 13: We extract the year from the
nowdate object using the%Ystring directive.