0

I'm iterating over a list of lists in python, and I want to change the date format for some of the elements of the nested list. I tried:

for dividend in dividend_data:
    for date in dividend[1], dividend[3], dividend[4], dividend[5]:
        date = datetime.strptime(date, '%m/%d/%Y').strftime("%Y-%m-%d")

but the "date" variable doesn't carry back to the original list elements. I can do this by handling them individually:

dividend[1] = datetime.strptime(dividend[1], '%m/%d/%Y').strftime("%Y-%m-%d")
dividend[3] = datetime.strptime(dividend[3], '%m/%d/%Y').strftime("%Y-%m-%d")
dividend[4] = datetime.strptime(dividend[4], '%m/%d/%Y').strftime("%Y-%m-%d")
dividend[5] = datetime.strptime(dividend[5], '%m/%d/%Y').strftime("%Y-%m-%d")

But, there must be a better way to handle this, right?

Troy D
  • 2,093
  • 1
  • 14
  • 28

4 Answers4

1

I don't think that you are actually changing the date variable. In

for date in dividend[1], dividend[3], dividend[4], dividend[5]:

You are creating a variable called date. Changing this variable is not the same as changing the actual value in that array. What you may need to do is

for i in 1, 3, 4, 5:
    dividend[i] = datetime.strptime(dividend[i], '%m/%d/%Y').strftime("%Y-%m-%d")
JCollerton
  • 3,227
  • 2
  • 20
  • 25
0
for dividend in dividend_data:
    for index in (1,3,4,5):
        date = dividend[index]
        dividend[index] = datetime.strptime(date, '%m/%d/%Y').strftime("%Y-%m-%d")

What's happening is that you're not changing the list element, you're just assigning a new thing to a value of a local variable, which is quickly overwritten by the next thing, never affecting the list.

So, grab the index and do it like above, changing the item in the list rather than just assigning a new variable.

James
  • 2,843
  • 1
  • 14
  • 24
0

This doesn't really have anything to do with nested lists, but lists in general. You can edit them in place, but you can't do it with a copy of the element.

for idx in (1,3,4,5):
    dividend[idx] = datetime.strptime(dividend[idx], '%m/%d/%Y').strftime("%Y-%m-%d")
Andrew Jaffe
  • 26,554
  • 4
  • 50
  • 59
0

Use the index instead. The problem is that date is a separate variable from the value in the array, so setting it equal to the new date format just reassigns that variable. Try this instead:

for dividend in dividend_data:
    for date_num in range(1, 6):
        dividend[date_num] = datetime.strptime(dividend[date_num], '%m/%d/%Y').strftime("%Y-%m-%d")
qfwfq
  • 2,416
  • 1
  • 17
  • 30