如何在Python中的几天,几小时,几周和几个月后迭代一次?

时间:2008-09-30 15:35:23

标签: python datetime

如何在数天,数小时,数周或数月之后迭代一段时间?

类似的东西:

for date in foo(from_date, to_date, delta=HOURS):
    print date

其中foo是一个函数,返回一个迭代器。我一直在查看日历模块,但这只适用于特定年份或月份,而不是日期之间。

7 个答案:

答案 0 :(得分:93)

使用dateutil及其rrule实现,如下所示:

from dateutil import rrule
from datetime import datetime, timedelta

now = datetime.now()
hundredDaysLater = now + timedelta(days=100)

for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater):
    print dt

输出

2008-09-30 23:29:54
2008-10-30 23:29:54
2008-11-30 23:29:54
2008-12-30 23:29:54

每月,每月,每周,每日,每小时,每分钟或每日更换一次。替换dtstart,直到你想要的任何日期时间对象。

此配方具有适用于所有情况的优势,包括每月。我能找到的唯一警告是,如果你传递的是所有月份都不存在的天数,它会跳过这几个月。

答案 1 :(得分:41)

我认为Python库中没有方法,但您可以使用datetime模块轻松创建一个方法:

from datetime import date, datetime, timedelta

def datespan(startDate, endDate, delta=timedelta(days=1)):
    currentDate = startDate
    while currentDate < endDate:
        yield currentDate
        currentDate += delta

然后你可以像这样使用它:

>>> for day in datespan(date(2007, 3, 30), date(2007, 4, 3), 
>>>                     delta=timedelta(days=1)):
>>>     print day
2007-03-30
2007-03-31
2007-04-01
2007-04-02

或者,如果您希望缩小delta:

>>> for timestamp in datespan(datetime(2007, 3, 30, 15, 30), 
>>>                           datetime(2007, 3, 30, 18, 35), 
>>>                           delta=timedelta(hours=1)):
>>>     print timestamp
2007-03-30 15:30:00
2007-03-30 16:30:00
2007-03-30 17:30:00
2007-03-30 18:30:00

答案 2 :(得分:6)

对于几个月的迭代,你需要一个不同的食谱,因为timedeltas不能表达“一个月”。

from datetime import date

def jump_by_month(start_date, end_date, month_step=1):
    current_date = start_date
    while current_date < end_date:
        yield current_date
        carry, new_month = divmod(current_date.month - 1 + month_step, 12)
        new_month += 1
        current_date = current_date.replace(year=current_date.year + carry,
                                            month=new_month)

(注意:您必须从模拟操作的月份中减去1,然后将其添加回new_month,因为datetime.date中的月份从1开始。)

答案 3 :(得分:2)

我使用pandas和datetime库实现了这个目的,如下所示。这对我来说更方便。

import pandas as pd
from datetime import datetime


DATE_TIME_FORMAT = '%Y-%m-%d %H:%M:%S'

start_datetime = datetime.strptime('2018-05-18 00:00:00', DATE_TIME_FORMAT)
end_datetime = datetime.strptime('2018-05-23 13:00:00', DATE_TIME_FORMAT)

timedelta_index = pd.date_range(start=start_datetime, end=end_datetime, freq='H').to_series()
for index, value in timedelta_index.iteritems():
    dt = index.to_pydatetime()
    print(dt)

答案 4 :(得分:0)

月迭代方法:

- (void)reloadUI {

  if (languageIsChanged == YES) {

     [self reloadRTLView:self.view];
  }
}


  - (void)reloadRTLView:(UIView *)view {

    [self changeViewRTL:view];
    for (UIView *tempView in view.subviews) {

        [self reloadRTLView:tempView];
    }
}

- (void)changeViewRTL:(UIView*)tempView {

    for (NSLayoutConstraint *constrain in tempView.constraints) {

        NSLayoutAttribute firstAttribute = constrain.firstAttribute;
        NSLayoutAttribute secondAttribute = constrain.secondAttribute;

        if ((firstAttribute == NSLayoutAttributeLeading || firstAttribute == NSLayoutAttributeTrailing) && (secondAttribute == NSLayoutAttributeLeading || secondAttribute == NSLayoutAttributeTrailing)) {

            if (firstAttribute == NSLayoutAttributeLeading) {
                firstAttribute = NSLayoutAttributeTrailing;
            } else if (firstAttribute == NSLayoutAttributeTrailing) {
                firstAttribute = NSLayoutAttributeLeading;
            }

            if (secondAttribute == NSLayoutAttributeLeading) {
                secondAttribute = NSLayoutAttributeTrailing;
            } else if (secondAttribute == NSLayoutAttributeTrailing) {
                secondAttribute = NSLayoutAttributeLeading;
            }

            constrain.constant *= -1;
            NSLayoutConstraint *constrainNew =  [NSLayoutConstraint constraintWithItem:constrain.firstItem attribute:firstAttribute relatedBy:constrain.relation toItem:constrain.secondItem attribute:secondAttribute multiplier:constrain.multiplier constant:constrain.constant];
            [tempView removeConstraint:constrain];
            [tempView addConstraint:constrainNew];
        }
    }
}

更多的代码,但它可以很好地处理长时间检查给定日期是否正常...

答案 5 :(得分:-1)

这个库提供了一个方便的日历工具:mxDateTime,这应该足够了:)

答案 6 :(得分:-2)

您应修改此行以使其正常工作:

current_date = current_date.replace(year = current_date.year + carry,month = new_month,day = 1)