0

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)

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, but it is not working. Applied exactly the same code and now get the "TypeError: 'builtin_function_or_method' object is not subscriptable".
Sorry about that, I used [], instead of (). I've updated this line in my answer: myNewList.append(timestamp)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.