0

我正在尝试读取一个 csv 文件,该文件是运行Autoruns autorunsc 命令行(即 autorunsc -a -m -c > mycsv.csv)的结果,并以我得到最新日期/时间的方式按时间排序就像在 excel 中一样位于顶部。

到目前为止,我已经弄清楚了如何通过使用Recoder python 类将其读取为 UTF16 将其重新编码为 utf 8 来将其转换为 csv 文件而不会出现编码错误。

import sys
import csv
import operator
import codecs

class Recoder(object):
    def __init__(self, stream, decoder, encoder, eol='\r\n'):
        self._stream = stream
        self._decoder = decoder if isinstance(decoder, codecs.IncrementalDecoder) else codecs.getincrementaldecoder(decoder)()
        self._encoder = encoder if isinstance(encoder, codecs.IncrementalEncoder) else codecs.getincrementalencoder(encoder)()
        self._buf = ''
        self._eol = eol
        self._reachedEof = False

    def read(self, size=None):
        r = self._stream.read(size)
        raw = self._decoder.decode(r, size is None)
        return self._encoder.encode(raw)

    def __iter__(self):
        return self

    def __next__(self):
        if self._reachedEof:
            raise StopIteration()
        while True:
            line,eol,rest = self._buf.partition(self._eol)
            if eol == self._eol:
                self._buf = rest
                return self._encoder.encode(line + eol)
            raw = self._stream.read(1024)
            if raw == '':
                self._decoder.decode(b'', True)
                self._reachedEof = True
                return self._encoder.encode(self._buf)
            self._buf += self._decoder.decode(raw)
    next = __next__

    def close(self):
        return self._stream.close()


writer = open('mycsv1.csv, 'wb')
f = open('mycsv.csv','rb'):
sr = Recoder(f, 'utf-16', 'utf-8')
s = sorted(csv.reader(sr), key=operator.itemgetter(0), reverse=True))

for row in s:
    print >> writer, row[0], ",", row[1], "," row[2]

问题是这只是从外观上按月排序。假设我在 2010 年、2011 年、2012 年的第 1-6 个月有条目。

它将仅按月份排序,不包括时间或日期,以便我仅获得最新日期。相反,我得到 1/1/2010、1/1/2011、1/1/2012、2/1/2010、2/1/2011、2/1/2012。

如果我在 excel 中对其进行排序,它将首先给我最新的日期/时间,如果它是基于 6 月的这个月(2012 年 6 月 1 日、2012 年 5 月 1 日、2012 年 4 月 1 日等) .) 任何有关如何使用 python 完成此操作的帮助都非常感谢。

更新

我正在使用的示例数据来自 autorunsc 格式化为 utf8 后。CSV 中的数据应如下所示:

Time, Entry Location, Entry, Enabled, Category, Description, Publisher, Launch String
6/23/2011 14:23, HKLM\System\CurrentControlSet\Services, JavaQuickStarterService, enabled, Services, Prefetches JRE files for faster startup, Oracle Corporation, C:\Program Files\java, C:\Program Files\Java\jre\blah
5/25/2006 1:14,,,,,,,,,
4/4/2003 22:10,,,,,,,,,
4/17/2006 11:11,,,,,,,,
0,,,,,,,,, (Some of the entries do not have date values and are null or blank.
6/10/2013 9:30,,,,,,,,,
6/23/2013 10:25,,,,,,,,,
etc

这些条目中的大多数都有值,但我不想复制和粘贴所有内容。我基本上想像excel一样从最新的日期/时间对日期进行排序。下面有人提到的 lambda 选项出错,因为它首先从列中读取“时间”。我想弄清楚如何跳过第一行并在其他日期/时间值上使用 lambda 以进行适当的排序。

4

2 回答 2

1

好的,之前没有完全理解是怎么回事。你的问题是你的“日期”仍然是字符串并且被排序。我猜你的日期格式是月/日/年(美国日期样式),因为你说它是按月排序的。您需要做的就是将日期解析为日期时间对象以解决排序问题。

# add this import at the top of your file
from datetime import datetime

# replace your current call to sorted with:
s = sorted(csv.reader(sr), key=lambda x:datetime.strptime(x[0],"%m/%d/%Y"), reverse=True))
于 2013-06-21T20:12:01.010 回答
0

您可以使用pandas模块和to_datetime()方法。

代码 :

import pandas as pd

data = pd.read_csv('mycsv.csv')
data['Time'] = pd.to_datetime(data['Time'], format="%m/%d/%Y %H:%M")

data = data.sort_values(by='Time', ascending=False)
print(data.to_csv(index=False))

输入: mycsv.csv

Time, Field
6/23/2011 14:23, ABC
5/25/2006 1:14, XYZ
4/4/2003 22:10, PQR
4/17/2006 11:11,GHI
, 0
, 1
6/10/2013 9:30, 2
6/23/2013 10:25, 3

输出 :

Time, Field
2013-06-23 10:25:00, 3
2013-06-10 09:30:00, 2
2011-06-23 14:23:00, ABC
2006-05-25 01:14:00, XYZ
2006-04-17 11:11:00,GHI
2003-04-04 22:10:00, PQR
, 0
, 1
于 2016-07-29T01:54:21.510 回答