0

I need to iterate through a list of date values in Python and get two dates at a time.

Something along the lines of

import datetime

listdates=[datetime.date(2022, 2, 10),datetime.date(2022, 2, 11),datetime.date(2022, 2, 12),datetime.date(2022, 2, 13),datetime.date(2022, 2, 14)]

for a in listdates:
    print(a,next(a))

The problem is that Python doesn't seem to support iterating through dates like this (see error below)

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_1868/3080882783.py in <module>
      2 
      3 for a in listdates:
----> 4     print(a,next(a))

TypeError: 'datetime.date' object is not an iterator

I'm sure there is something I am missing here, but I need these in date format because I need to pass the date values to a different procedure.

Do I need to do something like convert the values to text and back to dates again? Seems like an awful hack.

Any help would be very much appreciated

  • `itertools.pairwise` provides this functionality directly (though only on 3.10+). The `itertools` module docs for pre-3.10 provide a recipe for `pairwise` on older Python though. – ShadowRanger Jul 13 '22 at 00:01

2 Answers2

2

Is this what you want to do?

import datetime
listdates=[
    datetime.date(2022, 2, 10),
    datetime.date(2022, 2, 11),
    datetime.date(2022, 2, 12),
    datetime.date(2022, 2, 13),
    datetime.date(2022, 2, 14)
]

for i in range(len(listdates)-1):
    print(listdates[i],listdates[i+1])

Output:

2022-02-10 2022-02-11
2022-02-11 2022-02-12
2022-02-12 2022-02-13
2022-02-13 2022-02-14

Iterators are pointers to the elements of your list. You cant use next on the elements of the list - unless they are iterators themselves.

When you do for x in my_list, x is an element of the list, not an iterator.

That's why you are getting the error, the type date is not an iterator:

'datetime.date' object is not an iterator

This is valid:

l = [1,2,3,4]
my_iterator = iter(l)
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))

This is not:

l = ['a','b','c','d']
a = l[0]
print(next(a))
Nilo Araujo
  • 725
  • 6
  • 15
0

If I understand you correctly, you want to add one day to the date:

one_day = datetime.timedelta(days=1)

for d in listdates:
    print(d, d + one_day)

Prints:

2022-02-10 2022-02-11
2022-02-11 2022-02-12
2022-02-12 2022-02-13
2022-02-13 2022-02-14
2022-02-14 2022-02-15
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91