【问题标题】:Sort CSV lines by time in format "Oct 03 10:06:20" in Python在 Python 中以“Oct 03 10:06:20”格式按时间对 CSV 行进行排序
【发布时间】:2019-07-21 08:50:53
【问题描述】:

所以我已经为此寻找解决方案,但似乎找不到适合我的解决方案。

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

...

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

【问题讨论】:

  • 您可以使用usecols=[1,2] 并为您的打印语句print("{} | {} | {}".format(i, temp[i], df[2][i]))...(while 需要不缩进)。

标签: python csv sorting date


【解决方案1】:

不要将日期与其他数据分开。修改您的排序键,使其获取行的第二项,并将行传递给它。

应该这样做:

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

【讨论】:

  • 谢谢,这是否意味着我需要删除 usecols=[1] ?
  • 可能。我无法完全测试它
猜你喜欢
  • 2020-02-22
  • 1970-01-01
  • 2021-06-02
  • 2021-07-21
  • 2010-12-18
  • 2011-01-06
  • 2012-04-12
  • 2023-03-12
  • 2017-12-05
相关资源
最近更新 更多