2

I have a list of dates, written as strings, called depart_date

depart_date = ['3/1/2012', '3/4/2012', '3/11/2012']

etc.

I'd like to convert them to date objects. This is what I have:

for i in depart_date:
    dep_date = datetime.strptime(depart_date[i], '%m/%d/%Y')

and it gives me the TypeError: list indices must be integers, not str. I'm not sure why I'm getting this error because I thought the strptime function was supposed to convert strings into date objects.

Any help??

clcto
  • 9,530
  • 20
  • 42
python_amateur
  • 85
  • 1
  • 1
  • 7
  • `i` is the value, not the index, so replace `depart_date[i]` with `i`, and it will probably be worthwhile to rename `i` to `cur_date` or something – clcto Jun 23 '15 at 19:56
  • I have edited your question to include the language tag based on the syntax in the question. If this is the incorrect language, please update it. – clcto Jun 23 '15 at 20:12

1 Answers1

0

You need to add .Length

for i in depart_date.Length:
    dep_date = datetime.strptime(depart_date[i], '%m/%d/%Y')

Alternative:

for i in depart_date:
    dep_date = datetime.strptime(i, '%m/%d/%Y')
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37
  • I'm not super familiar with javascript, but i just know it has to be something along the lines of that. I think `i` has to be an enumerated value directly out of the variable you pass after `in`. That's why i posted the second alternative. It seems similar to the C# `foreach`, and in that case, you would have to do it as my second example. – maraaaaaaaa Jun 23 '15 at 20:04
  • I'm fairly certain this is python, not javascript. Javascript notation is [`for( variable in object ) { }`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) – clcto Jun 23 '15 at 20:10