ADVERTISEMENT
ADVERTISEMENT

Python datetime __str__() Method with Example

Python datetime.__str__() Method: Here, we are going to learn about the __str__() method of datetime class in Python with its definition, syntax, and examples.
Submitted by Hritika Rajput, on May 03, 2020

Python datetime.__str__() Method

datetime.__str__() method is used to manipulate objects of datetime class of module datetime.

It uses a datetime class object and returns a string representation of the object. For a datetime 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 datetime

Syntax:

    str()

Parameter(s):

  • None

Return value:

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

Example:

## importing datetime class
from datetime import datetime
import pytz

## Creating an instance
x = datetime.now()
d = str(x)
print("Original object:",x)
print("Date String:", d)
print()

## str function also uses the ISO format
x = datetime(2020, 1, 27, 23, 12, 24, 4566)
print("Date string of date 2020/1/27 and time 23:12:24  :", str(x))
print()

x = datetime(200, 1, 2, 3, 12, 24, 4566)
timezone = pytz.timezone('Asia/Tokyo')
x = x.astimezone(timezone)
print("Date string of date 200/1/2 and time 3:12:24 with tzinfo present :", str(x))
print()

## str(x) is equivalent to x.isoformat() function
x = datetime(200,10,12)
print("Datetime 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-05-03 16:45:16.315525
Date String: 2020-05-03 16:45:16.315525

Date string of date 2020/1/27 and time 23:12:24  : 2020-01-27 23:12:24.004566

Date string of date 200/1/2 and time 3:12:24 with tzinfo present : 0200-01-02 12:31:24.004566+09:19

Datetime in ISO 8601 format using isoformat() function: 0200-10-12 00:00:00
Date string 200/10/12  using str() function: 0200-10-12 00:00:00
True
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.