Python datetime __str__() Method with Example

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

Python datetime.__str__() Method

The datetime.__str__() method is used to get the string representation of the object. It uses a datetime class object. For a datetime object d, str(d) is equivalent to d.isoformat(' '). str().

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 datetime

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 datetime object.

Example for DateTime Object to String Representation in Python

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



Comments and Discussions!

Load comments ↻





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