为什么在python中比较两个日期时会出现TypeError?
我正在尝试编写一些代码,从一个超过30天的文件夹中删除所有文本文件 我是python新手,我知道下面的代码不是最干净的。我最初的代码更整洁,例如 datetime.datetime.now()和time.ctime(os.path.getctime(foundfile))转换为变量,但我认为这是导致错误的原因:为什么在python中比较两个日期时会出现TypeError?,python,datetime,Python,Datetime,我正在尝试编写一些代码,从一个超过30天的文件夹中删除所有文本文件 我是python新手,我知道下面的代码不是最干净的。我最初的代码更整洁,例如 datetime.datetime.now()和time.ctime(os.path.getctime(foundfile))转换为变量,但我认为这是导致错误的原因:TypeError:无法将datetime.datetime与str进行比较。。但似乎即使使用下面的直接方法,我仍然会遇到此错误 导入操作系统 导入时间 导入日期时间 对于os.listd
TypeError:无法将datetime.datetime与str进行比较。
。但似乎即使使用下面的直接方法,我仍然会遇到此错误
导入操作系统
导入时间
导入日期时间
对于os.listdir(“/MyDir/”)中的文件:
foundfile=os.path.join('/MyDir/',file)
如果文件.endswith('txt')和time.ctime(os.path.getctime(找到
文件()
我希望代码从当前日期减去30天,然后删除所有较旧的文本文件,但我得到了一个错误:
TypeError:can't compare datetime.datetime to str
。我不知道为什么。从time.ctime(os.path.getctime(find file))中获得的值
是一个字符串。您需要将此对象转换为python的datetime对象以比较这两个对象。您可以使用datetime.dateime.strptime()
方法进行此操作
import datetime
x = time.ctime(os.path.getctime(found file))
x = x.strftime('%Y-%m-%d %H:%M:%S')
x = datetime.datetime.strptime(x,'%Y-%m-%d %H:%M:%S')
然后比较if
语句中的这个datetime对象“x”。ctime()返回一个字符串,而不是datetime对象。请参阅
但是你为什么还要使用time.ctime()
os.path.getctime()
将时间作为unix时间戳返回。您可以使用datetime.datetime.utcfromtimestamp()
将其转换为日期时间,即
datetime.datetime.utcfromtimestamp(os.path.getctime(foundfile)))
这可以直接用于与其他datetime对象进行比较。其他答案可以工作,但它们将时间戳(float)转换为字符串并转换为datetime,而我们跳过一步,直接从时间戳转换为datetime
那么您的代码将变成:
import os
import time
import datetime
for file in os.listdir('/MyDir/'):
foundfile = os.path.join('/MyDir/', file)
if file.endswith('txt') and (datetime.datetime.utcfromtimestamp(os.path.getctime(foundfile)) < (datetime.datetime.now() - datetime.timedelta(days=30))):
os.remove(os.path.join('/MyDir/', file))
导入操作系统
导入时间
导入日期时间
对于os.listdir(“/MyDir/”)中的文件:
foundfile=os.path.join('/MyDir/',file)
如果文件.endswith('txt')和(datetime.datetime.utcfromtimestamp(os.path.getctime(foundfile))<(datetime.datetime.now()-datetime.timedelta(days=30)):
删除(os.path.join(“/MyDir/”,文件))
或者,为了让它更具可读性:
import os
import datetime as dt
for file in os.listdir('/MyDir/'):
foundfile = os.path.join('/MyDir/', file)
filecreation = dt.datetime.utcfromtimestamp(os.path.getctime(foundfile))
cutofftime = dt.datetime.now() - dt.timedelta(days=30)
if (file.endswith('txt') and (filecreation < cutofftime)):
os.remove(os.path.join('/MyDir/', file))
导入操作系统
将日期时间导入为dt
对于os.listdir(“/MyDir/”)中的文件:
foundfile=os.path.join('/MyDir/',file)
filecreation=dt.datetime.utcfromtimestamp(os.path.getctime(foundfile))
截止时间=dt.datetime.now()-dt.timedelta(天=30)
如果(file.endswith('txt')和(filecreation
函数time.ctime返回一个字符串,而您正试图将其与datetime.datetime的实例进行比较
如果您想比较,我建议您将ctime转换为时间。您可以使用来自answer的以下函数:
datetime\u from\u ctime=datetime.datetime.strtime(ctime\u str,“%a%b%d%H:%M:%S%Y”)
谢谢!非常有用。我不知道时间戳是一种特定的unix表示法。(虽然我正在unix上运行应用程序)。谢谢你指出这一点。我很高兴,我很高兴我能帮上忙:)我不认为它是一种特定的unix表示法,我想这就是它的名称(虽然我不知道为什么,这是一个有趣的问题)-它也被称为,基本上是自1970年1月1日以来的秒数。