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?
CodePudding user response:
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.
CodePudding user response:
Because you only print date once after the entire process is complete. If you put the print statement in the loop it will print all 12 dates.
CodePudding user response:
The code is setting he value of date in each iteration of the loop, so when the loop is completed, date will hold the last value it was set to.
If you print out its value within the loop you'll see the value changing for each execution.
import 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.datetime.strptime(a[i], "%d-%b-%y")
print(date)