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 |
date.strftime(format)
format
: This is a string format.It returns a string representing date
and time
object.
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)
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.