代码之家  ›  专栏  ›  技术社区  ›  Zinngg

我正在读一本书。csv文件,其中包含按时间戳、车牌、车辆类型和出入境顺序排列的数据

  •  1
  • Zinngg  · 技术社区  · 9 年前

    我需要将时间戳存储在列表中以供进一步操作,并编写了以下代码:

        import csv
        from datetime import datetime
    
        from collections import defaultdict
        t = []
        columns = defaultdict(list)
        fmt = '%Y-%m-%d %H:%M:%S.%f'
        with open('log.csv', 'r') as f:
            reader = csv.reader(f, delimiter=',')
            for row in reader:
                #t = row[1]
                for i in range(len(row)):
                    columns[i].append(row[i])
    
                if (row):
                    t=list(datetime.strptime(row[0],fmt))
    
    
        columns = dict(columns)
    
        print (columns)
        for i in range(len(row)-1):
    
            print (t)
    

    但我得到了一个错误:

        Traceback (most recent call last):
      File "parking.py", line 17, in <module>
        t = list(datetime.strptime(row[0],fmt))
    TypeError: 'datetime.datetime' object is not iterable
    

    如何将每个时间戳存储在列表的列中?

    这是示例日志文件

    2011-06-26 21:27:41.867801,KA03JI908,Bike,Entry
    2011-06-26 21:27:42.863209,KA02JK1029,Car,Exit
    2011-06-26 21:28:43.165316,KA05K987,Bike,Entry
    
    2 回复  |  直到 9 年前
        1
  •  0
  •   Ajay Goyal    9 年前

    如果你有一个csv文件,为什么不使用熊猫来获得你想要的。您的问题代码可能是这样的。

    import Pandas as pd
    df=pd.read_csv('log.csv')
    timestamp=df[0]
    

    如果csv的第一列具有时间戳,则您有一个数组,其中列表中第一列中的所有条目都称为时间戳。

    在此之后,您可以使用datetime将此列表的所有条目转换为时间戳对象。日期时间。strTime()。

    希望这有帮助。

        2
  •  0
  •   kchawla-pi    9 年前

    我还不能就澄清发表评论。 这段代码会在列表中为您提供时间戳吗?如果是,请提供csv文件中的几行数据。

    from datetime import datetime
    
    timestamps = []
    with open(csv_path, 'r') as readf_obj:
        for line in readf_obj:
            timestamps.append(line.split(',')[0])
    fmt = '%Y-%m-%d %H:%M:%S.%f'
    datetimes_timestamps = [datetime.strptime(timestamp_, fmt) for timestamp_ in timestamps]