title: Python: iterate through two datetimes hourly
body: <p>Here's the question:</p>
  
  <p>Using python's datetime module, create an iterator that generates all the hours between two datetime.datatime objects.</p>
  
  <p><code>it = hourly_it( d1, d2)</code> # where <code>d1</code> and <code>d2</code> are <code>datetime.datetime</code> objects. 
  For example,</p>
  
  <pre><code>from datetime import datetime
  it = hourly_it( datetime(2018, 10, 2, 12), datetime(2018, 10, 3, 12))
  </code></pre>
  
  <p>will generates all the date times between 12:00 (noon) Novermber 2, to 12:00 (noon) November 3rd.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>from datetime import date, timedelta as td, datetime
     def hourly_it( d1, d2) :
        start = d1
        finish = d2
        def f():
           nonlocal start, finish
           if(start&gt;=finish): return None
           start += td(hours=1)
           return start   
        return f
  </code></pre>
  
  <p>when I test the code using:</p>
  
  <pre><code>from datetime import datetime
    it = hourly_it( datetime(2018, 10, 2, 12), datetime(2018, 10, 3,12))
    print(next(it))
  </code></pre>
  
  <p>I get this error:</p>
  
  <blockquote>
    <p>TypeError                                 Traceback (most recent call
    last)</p>
    
    <p> in ()
          1 from datetime import datetime
          2 it = hourly_it( datetime(2018, 10, 2, 12), datetime(2018, 10, 3, 12))</p>
    
    <p>----> 3 print(next(it))</p>
    
    <p>TypeError: 'function' object is not an iterator</p>
  </blockquote>
  
  <p>I figured it out. Thanks all. Here is how you do it without using the generator. I should also note that I put the +1hour before the return and set the start >=</p>
  
  <pre><code>from datetime import date, timedelta as td, datetime
    def hourly_it( d1, d2) :
       start = d1
       finish = d2
       def f():
            nonlocal start, finish
            if(start&gt;=finish): return None
            start += td(hours=1)
            return start
  
        return iter(f,None)
  </code></pre>