[英]Why do I get a TypeError when comparing two datetimes in python?
我正在嘗試編寫一些代碼,從一個超過 30 天的文件夾中刪除所有文本文件。
我是 python 的新手,我知道下面的代碼不是最干凈的。 我的初始代碼更整潔,例如將 datetime.datetime.now() 和 time.ctime(os.path.getctime(foundfile) 放入變量中,但我認為這會導致錯誤: TypeError: can't compare datetime.datetime to str
但似乎即使使用下面的直接方法我仍然會收到此錯誤。
import os
import time
import datetime
for file in os.listdir('/MyDir/'):
foundfile = os.path.join('/MyDir/', file)
if file.endswith('txt') and time.ctime(os.path.getctime(found
file)) < datetime.datetime.now() - datetime.timedelta(days=30):
os.remove(os.path.join('/MyDir/', file))
我希望代碼從當前日期減去 30 天,然后刪除所有較舊的文本文件,但出現錯誤: TypeError: can't compare datetime.datetime to str
。 我不明白為什么。
time.ctime()
返回一個字符串,而不是日期時間 object。 請參閱文檔。
但是你為什么還要使用time.ctime()
呢?
os.path.getctime()
將時間作為 unix 時間戳返回。 您可以使用datetime.datetime.utcfromtimestamp()
將其轉換為日期時間,即
datetime.datetime.utcfromtimestamp(os.path.getctime(foundfile)))
這可以直接用於與其他日期時間對象進行比較。 其他答案有效,但它們將時間戳(浮點數)轉換為字符串到日期時間,而我們跳過一個步驟並直接從時間戳轉換為日期時間。
然后您的代碼將變為:
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))
或者,使其更具可讀性:
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))
您從time.ctime(os.path.getctime(found file))
獲得的值是一個字符串。 您需要將此 object 轉換為 python 的日期時間 object 以比較兩個對象。 您可以使用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 object 'x'
function time.ctime 返回一個字符串,而您試圖將其與 datetime.datetime 的實例進行比較
如果你想比較,我建議你將ctime轉換為時間。 您可以使用來自此答案的以下 function :
datetime_from_ctime = datetime.datetime.strptime(ctime_str, "%a %b %d %H:%M:%S %Y")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.