SHARE
TWEET

Untitled

a guest Aug 25th, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from datetime import datetime, timedelta
  2.  
  3.  
  4. class DateIterator:
  5.  
  6.     def __init__(self, from_date: datetime, to_date: datetime, interval: timedelta, closed: bool = True):
  7.         assert (from_date < to_date), 'to_date must be greater than from_date'
  8.  
  9.         self.from_date = from_date
  10.         self.to_date = to_date
  11.         self.interval = interval
  12.         self.closed = closed
  13.  
  14.         self.total_times = None
  15.         self.current_position = None
  16.         self._init_iterator()
  17.  
  18.     def _init_iterator(self):
  19.         self._calculate_total_times()
  20.         self.current_position = 0
  21.  
  22.     def _calculate_total_times(self):
  23.         self.total_times = (self.to_date - self.from_date) / self.interval
  24.         is_exact_fit = self.total_times.is_integer()
  25.         if not is_exact_fit and self.closed:
  26.             self.total_times += 1
  27.         self.total_times = int(self.total_times)
  28.  
  29.     def __iter__(self):
  30.         self._init_iterator()
  31.         return self
  32.  
  33.     def __next__(self):
  34.         if self.current_position >= self.total_times:
  35.             raise StopIteration
  36.  
  37.         interval_start_date = self.from_date + self.interval * self.current_position
  38.         interval_end_date = interval_start_date + self.interval
  39.         self.current_position += 1
  40.  
  41.         return interval_start_date, interval_end_date
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top