[英]Python: TypeError an integer is required(got type str)
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 is having value of date and time but while replace special char and having only date details it is giving error as integer is required. Datedetail 具有日期和时间的值,但是在替换特殊字符并且只有日期详细信息时,它会给出错误,因为需要 integer。
You cannot use the str.replace()
method on a datetime.datetime
class.您不能在datetime.datetime
class 上使用 str.replace str.replace()
方法。
Use str
to convert it into a string:使用str
将其转换为字符串:
print(str(Datedetail).replace('-','')[:6])
Output: Output:
202010
Recommendation: usestrftime
instead of datetime
.建议:使用strftime
代替datetime
。
The replace function is not the same as you use for strings.替换 function 与用于字符串的替换不同。 https://docs.python.org/2/library/datetime.html#datetime.date.replace https://docs.python.org/2/library/datetime.html#datetime.date.replace
You have to make it to a string first, so it has its usual behaviour: print(str(Datedetail).replace('-','')[:6])
你必须先把它变成一个字符串,所以它有它通常的行为: print(str(Datedetail).replace('-','')[:6])
But usually you would use string formatting as you can find as well in the documentation above: date.strftime(format)
但通常你会使用字符串格式,你可以在上面的文档中找到: date.strftime(format)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.