Skip to main content
 首页 » 编程设计

Python 按日期和时间对 CSV 进行排序

2025年05月04日13jiqing9006

好的,我有一个格式为 CSV 的文件:

   1 | Thu Oct 04 21:47:53 GMT+01:00 2018 | 35.3254 
   2 | Sun Oct 07 09:32:11 GMT+01:00 2018 | 45.7824 
   3 | Mon Oct 01 01:00:44 GMT+01:00 2018 | 94.1246 
 
  ... 
 
3023 | Sat Oct 23 01:00:44 GMT+01:00 2018 | 67.2007 

我想按日期和时间排序,所以我得到类似的东西:

... 
 
456 | Oct 16 23:25:06 | 45.6547 
457 | Oct 16 23:29:21 | 64.3453 
458 | Oct 16 23:34:17 | 27.6841 
459 | Oct 16 23:40:04 | 78.6547 
460 | Oct 16 23:44:18 | 11.6547 
461 | Oct 16 23:49:22 | 34.6547 
462 | Oct 16 23:54:15 | 37.6547 
463 | Oct 17 00:00:20 | 68.6547 
464 | Oct 17 00:05:06 | 07.6547 
465 | Oct 17 00:09:15 | 13.6547 
466 | Oct 17 00:14:45 | 37.6547 
467 | Oct 17 00:19:26 | 84.6547 
 
... 

日期和时间的格式很糟糕,所以我尝试了以下方法:

df = pd.read_csv(file, header=None, engine='c', delimiter=',' ) 
 
for index, row in df.iterrows(): 
    result = sorted(df.iterrows(),key=lambda row: datetime.strptime((str(row[1]))[9:24], "%b %d %H:%M:%S")) 
 
print (result) 

(例如 [9:24] 应该允许我拼接字符串以得到 Oct 16 23:29:21)

我遇到错误:

ValueError: time data 'ame: 0, dtype: ' does not match format '%b %d %H:%M:%S' 

我认为我的问题是我正在正确访问该行,但我似乎无法单独访问日期值(该行的第二个元素),因此排序无效。

任何想法将不胜感激!谢谢

请您参考如下方法:

您可以使用参数 infer_datetime_format。以下示例数据示例:

>> df['date'] = pd.to_datetime(df.date, infer_datetime_format = True) 
>> df.sort_values(by = 'date', ascending = True, inplace = True) 
>> df.date 
2   2018-10-01 02:00:44 
0   2018-10-04 22:47:53 
1   2018-10-07 10:32:11 
3   2018-10-23 02:00:44 
Name: date, dtype: datetime64[ns] 

来自 pandas.to_datetime()文档:

infer_datetime_format : boolean, default False

If True and no format is given, attempt to infer the format of the datetime strings, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by ~5-10x.