We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c84fb59 commit cf54dc1Copy full SHA for cf54dc1
4 files changed
CHANGELOG.md
@@ -6,6 +6,7 @@
6
7
- Added `on()` and `at()` methods which replace `with_date()` and `with_time()`.
8
- Added a `strict` keyword argument to `parse()` to get the type matching the parsed string.
9
+- Added the ability to pass an amount to the `range()` method to control the length of the gap.
10
11
### Changed
12
docs/_docs/period.rst
@@ -133,6 +133,19 @@ If you want to iterate over a period, you can use the ``range()`` method:
133
134
If you just want a generator you can use the ``xrange()`` method.
135
136
+You can pass an amount for the passed unit to control the length of the gap:
137
+
138
+.. code-block:: python
139
140
+ for dt in period.range('days', 2):
141
+ print(dt)
142
143
+ '2000-01-01T00:00:00+00:00'
144
+ '2000-01-03T00:00:00+00:00'
145
+ '2000-01-05T00:00:00+00:00'
146
+ '2000-01-07T00:00:00+00:00'
147
+ '2000-01-09T00:00:00+00:00'
148
149
You can also directly iterate over the ``Period`` instance, the unit will be ``days`` in this case:
150
151
.. code-block:: python
pendulum/period.py
@@ -183,10 +183,10 @@ def in_words(self, locale=None, separator=' '):
183
locale=locale, separator=separator, _periods=periods
184
)
185
186
- def range(self, unit):
187
- return list(self.xrange(unit))
+ def range(self, unit, amount=1):
+ return list(self.xrange(unit, amount))
188
189
- def xrange(self, unit):
+ def xrange(self, unit, amount=1):
190
method = 'add'
191
op = operator.le
192
if not self._absolute and self.invert:
@@ -195,13 +195,13 @@ def xrange(self, unit):
195
196
start, end = self.start, self.end
197
198
- i = 1
+ i = amount
199
while op(start, end):
200
yield start
201
202
start = getattr(self.start, method)(**{unit: i})
203
204
- i += 1
+ i += amount
205
206
def intersect(self, *periods):
207
"""
tests/period_tests/test_range.py
@@ -92,3 +92,16 @@ def test_range_with_dst(self):
92
self.assertPendulum(r[0], 2016, 10, 14, 0, 0, 0)
93
self.assertPendulum(r[2], 2016, 10, 16, 1, 0, 0)
94
self.assertPendulum(r[-1], 2016, 10, 21, 0, 0, 0)
95
96
+ def test_range_amount(self):
97
+ dt1 = Pendulum(2016, 10, 14, tzinfo='America/Sao_Paulo')
98
+ dt2 = dt1.add(weeks=1)
99
100
+ p = Period(dt1, dt2)
101
+ r = p.range('days', 2)
102
103
+ self.assertEqual(len(r), 4)
104
+ self.assertPendulum(r[0], 2016, 10, 14, 0, 0, 0)
105
+ self.assertPendulum(r[1], 2016, 10, 16, 1, 0, 0)
106
+ self.assertPendulum(r[2], 2016, 10, 18, 0, 0, 0)
107
+ self.assertPendulum(r[3], 2016, 10, 20, 0, 0, 0)
0 commit comments