【问题标题】:PYTHON 3.8 date rangePython 3.8 日期范围
【发布时间】:2019-10-25 10:23:10
【问题描述】:

我试图查找两个日期之间的所有日期,例如: 我有两个日期 2019-09-21 和 2019-10-09,我怎样才能得到这样的日期:

2019-09-21
2019-09-22
2019-09-23
2019-09-24
....
....
2019-10-08
2019-10-09

【问题讨论】:

  • @FlorianBernard,这个问题与寻找两个日期之间的差异无关,它更多的是关于产生一个范围内的所有日期。

标签: python loops date time


【解决方案1】:

下面的代码可以帮助你。

from datetime import datetime, timedelta
start_date = datetime.strptime('2019-09-21', '%Y-%m-%d').date()
end_date = datetime.strptime('2019-10-09', '%Y-%m-%d').date()
while start_date <= end_date:
    print(start_date)
    start_date = start_date+timedelta(days=1)

输出

2019-09-21
2019-09-22
2019-09-23
2019-09-24
2019-09-25
2019-09-26
2019-09-27
2019-09-28
2019-09-29
2019-09-30
2019-10-01
2019-10-02
2019-10-03
2019-10-04
2019-10-05
2019-10-06
2019-10-07
2019-10-08
2019-10-09

【讨论】:

    【解决方案2】:

    一种 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__ 构造函数任意复杂(例如,接受datetimedate 变量以及当前字符串)。

    最后一点需要额外解释。在设置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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多