简体   繁体   English

Python:TypeError 需要 integer(获取类型 str)

[英]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

Make use of.strftime() to get dates into format you want.利用 .strftime() 将日期转换为您想要的格式。

Datedetail.strftime('%Y%m')

在此处输入图像描述

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.

相关问题 Python:类型错误:需要一个整数(得到类型 str) - Python: TypeError: an integer is required (got type str) TypeError:Python中需要一个整数(类型为str) - TypeError: an integer is required (got type str) in python Python 2-如何修复TypeError:必须为整数(类型为str) - Python 2 - How to fix TypeError: an integer is required (got type str) TypeError:函数联接时需要一个整数(got type str)-python - TypeError: an integer is required (got type str) on function join - python TypeError:Python Selenium Webdri中需要一个整数(类型为str) - TypeError: an integer is required (got type str) in python selenium webdri python / flask:TypeError:需要一个整数(得到类型str) - python/flask: TypeError: an integer is required (got type str) Python Flask-TypeError:必须为整数(类型为str) - Python Flask - TypeError: an integer is required (got type str) 类型错误:在 Python 中打开文件时需要 integer(获取类型 str) - TypeError: an integer is required (got type str) when opening file in Python Pyarrow:TypeError:需要一个整数(得到类型 str) - Pyarrow: TypeError: an integer is required (got type str) TypeError:在Tkinter中需要一个整数(got类型str) - TypeError: an integer is required (got type str) in Tkinter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM