Python:TypeError需要一个整数(获取类型str)

2024-10-03 09:17:32 发布

您现在位置:Python中文网/ 问答频道 /正文

print(Datedetail) -> 2020-10-31 00:00:00
print(type(Datedetail) -> <class 'datetime.datetime'>
print (DateDetail.replace('-',''))[:6]) -> TypeError: an integer is required (got type str)

Datedetail的值为date和time,但当替换特殊字符且仅包含日期详细信息时,它会给出错误,因为需要整数


Tags: andatetimedateistyperequiredintegerreplace
3条回答

replace函数与用于字符串的函数不同。 https://docs.python.org/2/library/datetime.html#datetime.date.replace

您必须先将其设置为字符串,这样它就有了通常的行为: print(str(Datedetail).replace('-','')[:6])

但是通常您会使用字符串格式,正如您可以在上面的文档中找到的:date.strftime(format)

使用.strftime()将日期转换为所需的格式

Datedetail.strftime('%Y%m')

enter image description here

不能在datetime.datetime类上使用str.replace()方法

使用str将其转换为字符串:

print(str(Datedetail).replace('-','')[:6])

输出:

202010

建议:使用^{}代替datetime

相关问题 更多 >