问题描述
如下所示:
pre> for foo(from_date,to_date,delta = HOURS):
打印日期
其中foo是一个函数,返回一个迭代器。我一直在看日历模块,但只适用于一个特定的年份或月份,而不是日期之间。
使用及其rrule实现,如下所示:
from dateutil import rrule
/ pre>
from datetime import datetime,timedelta
now = datetime.now()
100DaysLater = now + timedelta days = 100)
在rrule.rrule中的dt(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,直到你想要的任何datetime对象。
这个配方在所有情况下都有优势,包括MONTHLY。只能注意到,如果你通过所有月份不存在的日数,它会跳过那些月份。
How do I iterate over a timespan after days, hours, weeks or months?
Something like:
for date in foo(from_date, to_date, delta=HOURS): print date
Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.
解决方案Use dateutil and its rrule implementation, like so:
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
Output is
2008-09-30 23:29:54 2008-10-30 23:29:54 2008-11-30 23:29:54 2008-12-30 23:29:54
Replace MONTHLY with any of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. Replace dtstart and until with whatever datetime object you want.
This recipe has the advantage for working in all cases, including MONTHLY. Only caveat I could find is that if you pass a day number that doesn't exist for all months, it skips those months.
这篇关于在Python中,如何在几天,几个小时,几周和几个月内迭代一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!