3

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?

asiehh
  • 553
  • 12
  • 22

1 Answers1

5

x must be a list:

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

then, you can append all your datetime objects. Or even more Pythonian:

x = [datetime.strptime(s, "%Y-%m-%d %H:%M:%S") for s in date_str]
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Thanks @schwobaseggl. I tried this before and when I print x, I get the following [datetime.datetime(2012, 11, 4, 1, 5, 21), datetime.datetime(2013, 11, 3, 1, 5, 21), datetime.datetime(2014, 11, 2, 1, 7, 31)] if I print x[1], it will give me the correct format. 2013-11-03 01:05:21 – asiehh Mar 08 '16 at 21:21
  • 1
    @AsiehHarati Yeah, if you print a list, it will use the `repr` method of its elements, and not the `str` which used when you print them directly. You can compare: `print repr(x[0]), str(x[0])` – user2390182 Mar 08 '16 at 21:26