-1
import datetime as dt
current_dates = ['09 May 2020', '10 May 2020', '11 May 2020', '15 May 2020']

for item in current_dates:
    date = item
    date = dt.datetime.strptime(item, '%d %b %Y')
    item = date
    print(current_dates)

I'm trying to convert the items in the current_dates list to datetime, but when I subsequently type type(current_dates[0] the program returns str

Tweep
  • 71
  • 1
  • 2
  • 9
  • 1
    Use list comprehension: `[dt.datetime.strptime(item, '%d %b %Y') for item in current_dates]`. – Henry Yik Jun 29 '20 at 03:48
  • 1
    the reason why the type in `current_dates` is not changed is because it's not mutated nor re-declared. You just iterate it in for loop. Either use a new variable to store the new datetime objects or use list comprehension as proposed above. – darkash Jun 29 '20 at 03:53
  • 1
    When you iterate through a list you use a copy of each element, not the reference of the same element in the list. So you have to reassign the values once computed. – MOHAMMED NUMAN Jun 29 '20 at 04:04

1 Answers1

0

You need to assign the new datetime values to the list

import datetime as dt
current_dates = ['09 May 2020', '10 May 2020', '11 May 2020', '15 May 2020']

current_dates = [dt.datetime.strptime(item, '%d %b %Y') for item in current_dates]

Albert Nguyen
  • 377
  • 2
  • 11
  • https://stackoverflow.com/questions/19290762/cant-modify-list-elements-in-a-loop-python – AMC Jun 29 '20 at 04:36