我有這個 csv 檔案,看起來像這樣;
datetime_period,value
01 Apr 2021 00:00,92.85
01 Apr 2021 00:30,91.73
11 Feb 2021 19:30,88.58
11 Feb 2021 20:00,88.58
13 Jan 2021 13:00,80.49
13 Jan 2021 13:30,81.95
我想根據 column 中的日期時間對此 csv 進行排序datetime_period。
我使用此鏈接按 python中的日期排序 csv 物件作為指南。
這是我的代碼;
data = csv.reader(open(csv_file_path, 'r'))
data = sorted(data, key=lambda row: datetime.strptime(row[0], "%d %b %Y %H:%M"))
我得到了錯誤;
ValueError: time data '???time_period' does not match format '%d %b %Y %H:%M'
python-BaseException
我查看了代碼并認為我的代碼與日期時間格式匹配。有人可以告訴我代碼有什么問題或提供替代解決方案嗎?謝謝你。
我正在使用 python 3.8.5
uj5u.com熱心網友回復:
您正在嘗試對不包含datetime值的標題行進行排序。
解決這個問題的一種方法是pop在排序之前關閉標題,然后將它們添加回來。
data = [line for line in csv.reader(open('test.csv', 'r'))]
headers = data.pop(0)
data = sorted(data, key=lambda row: datetime.strptime(row[0], "%d %b %Y %H:%M"))
#[['13 Jan 2021 13:00', '80.49'], ['13 Jan 2021 13:30', '81.95'], ['11 Feb 2021 19:30', '88.58'], ['11 Feb 2021 20:00', '88.58'], ['01 Apr 2021 00:00', '92.85'], ['01 Apr 2021 00:30', '91.73']]
out = [headers] data
#[['datetime_period', 'value'], ['13 Jan 2021 13:00', '80.49'], ['13 Jan 2021 13:30', '81.95'], ['11 Feb 2021 19:30', '88.58'], ['11 Feb 2021 20:00', '88.58'], ['01 Apr 2021 00:00', '92.85'], ['01 Apr 2021 00:30', '91.73']]
uj5u.com熱心網友回復:
您需要跳過檔案開頭的標題行。您可以通過將csv.reader物件傳遞給next()內置函式對其進行迭代來輕松做到這一點。下面的代碼顯示了如何執行此操作并在讀取檔案內容后正確關閉檔案。
import csv
from datetime import datetime
csv_file_path = 'time_data.csv'
with open(csv_file_path, 'r', newline='') as file:
reader = csv.reader(open(csv_file_path, 'r'))
next(reader) # Skip header.
data = sorted(reader, key=lambda row: datetime.strptime(row[0], "%d %b %Y %H:%M"))
print(data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331636.html
