一种 Python 风格的方法是创建一个迭代器,例如:
from datetime import datetime, timedelta
class dater(object):
def __init__(self, first, lastPlusOne, inclusiveEnd = False):
# Store important stuff, adjusting end if you want it inclusive.
self.__oneDay = timedelta(days = 1)
self.__curr = datetime.strptime(first, "%Y-%m-%d").date()
self.__term = datetime.strptime(lastPlusOne, "%Y-%m-%d").date()
if inclusiveEnd:
self.__term += self.__oneDay
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
# This is the meat. It checks to see if the generator is
# exhausted and raises the correct exception if so. If not,
# it saves the current, calculates the next, stores that
# for the next time, then returns the saved current.
if self.__curr >= self.__term:
raise StopIteration()
(cur, self.__curr) = (self.__curr, self.__curr + self.__oneDay)
return cur
你可以用类似的东西来调用它(来自你的例子):
for date in dater("2019-09-21", "2019-10-09", inclusiveEnd=True):
print(date)
得到:
2019-09-21
2019-09-22
2019-09-23
2019-09-24
2019-09-25
: no need to show it all, trust me :-)
2019-10-08
2019-10-09
使用迭代器的好处是:
- 使用它的代码变成了一个非常简单的
for循环,类似于Python的许多其他方法;和
- 您可以使
__init__ 构造函数任意复杂(例如,接受datetime 或date 变量以及当前字符串)。
最后一点需要额外解释。在设置self.__curr(例如)的代码中,您可以使用如下内容:
if type(first) == type(date(2000, 1, 1)): # copy a date.
self.__curr = first
elif type(first) == type(datetime(2000, 1, 1)): # extract date from datetime.
self.__curr = first.date()
else: # convert string.
self.__curr = datetime.strptime(first, "%Y-%m-%d").date()
这将检测源类型并调整行为,以便您获得date 无论如何。如果你对最后的日期做同样的事情,你会得到一个真正适应性强的迭代器,它甚至可以以不同的表示开始和结束:
for mydate in dater("2000-01-01", datetime.now()):
process_every_date_from_start_of_2000_to_yesterday(mydate)