create a list of datetime objects using datetime.strptime

Viewed 8182

I have a list of strings.

date_str = ["2012-11-04 1:05:21", "2013-11-03 1:05:21", "2014-11-02 1:07:31"]

I want to read them as datetime objects. For one string, I do

datetime.strptime(date_str[1], "%Y-%m-%d %H:%M:%S")

but I don't know how to create a list of datetime objects. If I use

datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")

I get this error:

TypeError: must be string, not list

I tried using a loop:

x = datetime.strptime(date_str[0], "%Y-%m-%d %H:%M:%S")
for i in range(1,len(date_str)):
    x.append(datetime.strptime(date_str[i], "%Y-%m-%d %H:%M:%S"))

but I get the following error

AttributeError: 'datetime.datetime' object has no attribute 'append'

Is there a way to create a list of datetime objects?

1 Answers
Related