Python datetime .__ str __()方法 (Python datetime.__str__() Method)
datetime.__str__() method is used to manipulate objects of datetime class of module datetime.
datetime .__ str __()方法用于操作模块datetime的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.
它使用日期时间类对象,并返回该对象的字符串表示形式。 对于日期时间对象d , str(d)等效于d.isoformat('')。 str()是一个实例方法,因为它使用类的实例。
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.
此方法的返回类型是代表原始datetime对象的字符串。
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
翻译自: https://www.includehelp.com/python/datetime-__str__-method-with-example.aspx