1
我在操作csv文件時遇到了問題。 在我的csv文件中,有一個'開始時間'和'完成時間'的列,我想使用它來獲得一個'持續時間'列。 當我嘗試duration = row[2] - row[1]
時,顯示錯誤信息Python - 如何在csv中獲得開始和結束時間列的'duration'列?
'unsupported operand type(s) for -: 'str' and 'str'
。
我在操作csv文件時遇到了問題。 在我的csv文件中,有一個'開始時間'和'完成時間'的列,我想使用它來獲得一個'持續時間'列。 當我嘗試duration = row[2] - row[1]
時,顯示錯誤信息Python - 如何在csv中獲得開始和結束時間列的'duration'列?
'unsupported operand type(s) for -: 'str' and 'str'
。
既然你從CSV文件中獲得的數據是STR型的,你不能做的操作:
duration = row[2] - row[1]
我會建議你先轉換行[2]和行[1]的內容,然後做手術。
import time
complete_time = time.strptime(row[2])
start_time = time.strptime(row[1])
duration = complete_time - start_time
你會在這裏發佈一些代碼,它會讓你更容易幫助你。另外,你不能計算字符串的差異,你需要先將它們轉換爲日期。查看['strptime'](https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime)。 – hlt
1)瞭解如何將CSV導入熊貓數據框 - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html。 2)在這裏閱讀如何使用熊貓的時間和日期 - http://pandas.pydata.org/pandas-docs/stable/timeseries.html 3)在這裏看到如何將熊貓數據框導出到csv:http ://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html –
請發佈您的代碼! – elena