a =['10-Sep-12','11-Sep-12','12-Sep-12','13-Sep-12','14-Sep-12','15-Sep-12','16-Sep-12','17- Sep-12','18-Sep-12','19-Sep-12','20-Sep-12','21-Sep-12','22-Sep-12','23-Sep-12']
for i in range (len(a)):
date = datetime.strptime(a[i], "%d-%b-%y")
Why this code only change datetime format for the last string of the list only?
print (date)
Output : 2012-09-23 00:00:00
How can I fix this code?
>Solution :
You are printing date outside the for loop that’s why you are getting the only the last value.
Do this and you’ll see that each string got converted to datetime.
a =['10-Sep-12','11-Sep-12','12-Sep-12','13-Sep-12','14-Sep-12','15-Sep-12','16-Sep-12','17-Sep-12','18-Sep-12','19-Sep-12','20-Sep-12','21-Sep-12','22-Sep-12','23-Sep-12']
for i in range (len(a)):
date = datetime.strptime(a[i], "%d-%b-%y")
print(date)
Whenever you run a loop the value of the variable changes each iteration. If you print that variable outside the loop, it’ll only print the last value of the variable. In your case being the value stored inside it in the 14th iteration.