Python date __str__() Method with Example

Python date.__str__() Method: In this tutorial, we will learn about the __str__() method of date class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 22, 2023

Python date.__str__() Method

The date.__str__() method 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

The following module is required to use __str__() method:

import datetime

Class

The following class is required to use __str__() method:

from datetime import date

Syntax

The following is the syntax of __str__() method:

str()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

The return type of this method is a string representing the original date.

Example of date __str__() Method in Python

## 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




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.