CodeIsland
CodeIsland

Reputation: 61

How save datetime objects in list (python, csv)

Can anyone please tell me how to save my parsed datetime objects to a list? Please see code after the last comment where the problem comes up - Why do I get the AttributeError: 'datetime.datetime' object has no attribute 'toList'? Thanks!

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)

Upvotes: 0

Views: 3842

Answers (1)

ionut
ionut

Reputation: 767

you should create the list before the for loop, and then add each element to it in the loop, like so:

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)

Upvotes: 1

Related Questions