如何将日期时间对象保存在列表中(Python,CSV)

时间:2019-04-13 18:25:24

标签: python list csv datetime timestamp

谁能告诉我如何将解析的日期时间对象保存到列表中?请在出现问题的最后注释后查看代码-为什么我得到AttributeError:'datetime.datetime'对象没有属性'toList'?谢谢!

from datetime import datetime, timedelta
import pandas as pd

from dateutil.parser import parse

csvFile = pd.read_csv('myFile.csv')
column = csvFile['timestamp']

column = column.str.slice(0, 19, 1)

dt1 = datetime.strptime(column[1], '%Y-%m-%d %H:%M:%S')

print("dt1", dt1) #output: dt1 2010-12-30 15:06:00

dt2 = datetime.strptime(column[2], '%Y-%m-%d %H:%M:%S')

print("dt2", dt2) #output: dt2 2010-12-30 16:34:00

dt3 = dt1 - dt2

print("dt3", dt3) #output: dt3 -1 day, 22:32:00

#works:
for row in range(len(column)):
    timestamp = datetime.strptime(column[row], '%Y-%m-%d %H:%M:%S')
    print("timestamp", timestamp) #output (excerpt): timestamp     2010-12-30 14:32:00 timestamp 2010-12-30 15:06:00

#trying to save all parsed timestamps in list, NOT WORKING
myNewList = timestamp.toList()
print(myNewList)

1 个答案:

答案 0 :(得分:0)

您应该在for循环之前创建列表,然后在循环中向其添加每个元素,如下所示:

myNewList = []
#works:
for row in range(len(column)):
    timestamp = datetime.strptime(column[row], '%Y-%m-%d %H:%M:%S')
    print("timestamp", timestamp) 
    myNewList.append(timestamp)

print(myNewList)