我使用 pandas 將 excel 檔案串列存盤到變數 excel_list
然后我試圖從excel表中獲取“日期”。這是我的代碼:
xls_list = []
for file in xls_list:
excel_list.append(pd.read_excel(file, sheet_name=None))
closed_between = excel_list[0]['Report Info'][excel_list[0]['Report Info'].columns[1]][(excel_list[0]['Report Info'].loc[excel_list[0]['Report Info']['Title']=='Closed Between'].index)]
我可以像下面這樣得到值:
3 03/01/2022 12:00 AM - 03/01/2022 11:59 PM 名稱:聊天摘要按時間、檔案夾、日期、資料型別:物件
但是,當我嘗試將日期切片或剝離時。我沒能做到。此代碼顯示錯誤:
dt.strptime(closed_between , '%m/%d/%Y')
結果:
-------------------------------------------------- ------------------------- ----> 1 dt.strptime(match , '%m/ 中的 AttributeError Traceback (最近一次呼叫最后一次) %d/%Y')
AttributeError: 模塊 'datetime' 沒有屬性 'strptime'
此代碼顯示沒有變化:
match[0:11]
結果:
3 03/01/2022 12:00 AM - 03/01/2022 11:59 PM 名稱:聊天摘要按時間、檔案夾、日期、資料型別:物件
我的目標是對字串中的第一個日期進行子串化。請幫助提高我的知識,謝謝。
uj5u.com熱心網友回復:
屬性錯誤
您可能匯入了日期時間,例如import datetime as dt. 這導致AttributeError: module 'datetime' has no attribute 'strptime'.
應該是from datetime import datetime as dt。然后你可以使用dt.strptime.
型別錯誤
大概你的 closed_between 是一個系列,而不是一個 str。它在錯誤中非常明確地說:...must be str, not Series.. 如果你知道你只得到一個值,你可以使用 dt.strptime(closed_between[0], '%m/%d/%Y')
其他問題
您不能只將帶有格式"%m/%d/%Y"的 strptime 應用于字串"03/01/2022 12:00 AM - 03/01/2022 11:59 PM",因為這種格式根本不匹配字串。您首先必須拆分字串,例如closed_between[0].split(" ")[0]給03/01/2022,然后您可以通過strptime 發送它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441133.html
