being inexperienced with Python I am unable to properly deal with the datetime objects, when wanting to iterate over them. I imported timestamps from a csv file and parsed them into datetime objects. Now I am unable to perform functions on them, because I get one error after the other. Please see my code, what causes the "TypeError: 'datetime.datetime' object is not iterable".
If there is no simple solution to my problem, can someone tell me how to save the datetime objects into a list?
The function of my code is inspired by this post, which works on date time objects from a list: Getting the closest date to a given date
Thanks in advance.
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
#parsing the timestamps as datetime objects 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
here error occurs:
base_date = dt1
def func(x):
d = x[0]
delta = d - base_date if d > base_date else timedelta.max
return delta
min(timestamp, key = func)