Home »
Python »
Python Reference »
Python date Class
Python date __str__() Method with Example
Python date.__str__() Method: Here, we are going to learn about the __str__() method of date class in Python with its definition, syntax, and examples.
Submitted by Hritika Rajput, on April 29, 2020
Python date.__str__() Method
date.__str__() method is used to manipulate objects of date class of module datetime.
It uses a date class object and returns a string representation of the object. For a date object d, str(d) is equivalent to d.isoformat(). str() is an instance method as it uses an instance of the class.
Module:
import datetime
Class:
from datetime import date
Syntax:
str()
Return value:
The return type of this method is a string representing the original date.
Example:
## importing date class
from datetime import date
## Creating an instance
x = date.today()
d = str(x)
print("Original object:",x)
print("Date String:", d)
print()
## str function also uses the ISO format
x = date(2020,10,1)
print("Date string of date 2020/10/1:", str(x))
print()
## str(x) is equivalent to x.isoformat() function
x = date(200,10,12)
print("Date 200/10/12 in ISO 8601 format using isoformat() function:", x.isoformat())
print("Date string 200/10/12 using str() function:", str(x))
print( x.isoformat() == str(x))
Output
Original object: 2020-04-29
Date String: 2020-04-29
Date string of date 2020/10/1: 2020-10-01
Date 200/10/12 in ISO 8601 format using isoformat() function: 0200-10-12
Date string 200/10/12 using str() function: 0200-10-12
True