Py学习  »  Python

按时间对csv行进行排序,python格式为“oct 03 10:06:20”

codeman • 5 年前 • 1587 次点击  

所以我寻找了一个解决办法,但似乎找不到适合我的方法。

我有一个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

不排序的,笨拙的日期和时间格式。

我想按日期和时间排序(没有列标题,只有原始数据)

我使用了以下代码:

temp = [] # to hold dates

df = pd.read_csv(file, header=None, usecols=[1], engine='c')

for row in df.iterrows():

    # grab date and time only
    new = (repr(row[1]))[9:24]
    temp.append(new)
    temp.sort(key=lambda date: datetime.strptime(date, "%b %d %H:%M:%S"))

    i = 0
    while i < len(temp):
        print(temp[i])
        i += 1

这将以更整洁的格式输出日期和时间,并进行排序:

...

Oct 16 23:25:06
Oct 16 23:29:21
Oct 16 23:34:17
Oct 16 23:40:04
Oct 16 23:44:18
Oct 16 23:49:22
Oct 16 23:54:15
Oct 17 00:00:20
Oct 17 00:05:06
Oct 17 00:09:15
Oct 17 00:14:45
Oct 17 00:19:26

...

但我正在努力写回csv并按该列对所有数据进行排序。

我想要的输出是编辑csv以获得如下内容:

...

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

...

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43529
 
1587 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Jean-François Fabre
Reply   •   1 楼
Jean-François Fabre    6 年前

不要将日期与其他数据分离。重新整理排序键,使其占据行的第二项,并将行传递给它。

它应该做到:

result = sorted(df.iterrows(),key=lambda row: datetime.strptime(row[1], "%b %d %H:%M:%S"))