如何使用Python生成重复日期?例如,我想为“每个第二个月的第三个星期五”生成重复日期。我想生成每日,每周,每月,每年的重复日期(即与Outlook Express中的重复功能相同)。
答案 0 :(得分:24)
import dateutil.rrule as dr
import dateutil.parser as dp
import dateutil.relativedelta as drel
start=dp.parse("19/02/2010") # Third Friday in Feb 2010
这会产生每个月的第三个星期五
rr = dr.rrule(dr.MONTHLY,byweekday=drel.FR(3),dtstart=start, count=10)
每隔三个星期五打印一次:
print map(str,rr)
# ['2010-02-19 00:00:00', '2010-03-19 00:00:00', '2010-04-16 00:00:00', '2010-05-21 00:00:00', '2010-06-18 00:00:00', '2010-07-16 00:00:00', '2010-08-20 00:00:00', '2010-09-17 00:00:00', '2010-10-15 00:00:00', '2010-11-19 00:00:00']
rr是可迭代的,因此您可以使用切片表示法来挑选其他所有项目。这将打印每隔一个月的第三个星期五 :
print map(str,rr[::2])
# ['2010-02-19 00:00:00', '2010-04-16 00:00:00', '2010-06-18 00:00:00', '2010-08-20 00:00:00', '2010-10-15 00:00:00']
上面,我使用str
来稍微美化输出。要获得更灵活的日期字符串格式,请使用strftime
:有关所有选项,请参阅http://au2.php.net/strftime或strftime的手册页。
print [d.strftime('%d/%m/%Y') for d in rr[::2]]
# ['19/02/2010', '16/04/2010', '18/06/2010', '20/08/2010', '15/10/2010']
答案 1 :(得分:0)
你可以试试dateutil - 特别是它的相对分数和套餐。
答案 2 :(得分:0)
您可以尝试自己写一下。您将首先需要一个迭代器,它生成以给定间隔分隔的日期:
import datetime
def dateiter(start, resolution):
date = start
while True:
yield date
date += resolution
现在,您可以生成日期并过滤它们:
# generate a list of every tuesday of february
# this iterates over every day from now, and filtered according to the rules
# warning: infinite generator below, there is nothing to end the iteration
tuesdays_of_february = (date for date in dateiter(datetime.datetime.now(), datetime.timedelta(days=1)) if date.weekday() == 4 and date.month == 2)
你可以自己调用迭代器,直到你有足够的日期:
>>> next(tuesdays_of_february)
datetime.datetime(2010, 2, 19, 14, 25, 46, 171000)
现在,您需要限制结果:
>>> from itertools import *
>>>
>>> # get the five next valid dates:
>>> list(islice(tuesdays_of_february),5)
[datetime.datetime(2010, 2,26, 14, 25, 46, 171000), datetime.datetime(2011, 2, 4
, 14, 25, 46, 171000), datetime.datetime(2011, 2, 11, 14, 25, 46, 171000), datet
ime.datetime(2011, 2, 18, 1 4, 25, 46, 171000), datetime.datetime(2011, 2, 25
, 14, 25, 46, 171000)]
>>>
>>> # or until a condition is met:
>>> list(takewhile( lambda date: date.year < 2014, tuesdays_of_february ))
[datetime.datetime(2012, 2, 3, 14, 25, 46, 171000), datetime.datetime(2012, 2, 1
0, 14, 25, 46, 171000), datetime.datetime(2012, 2, 17, 14, 25, 46, 171000), date
time.datetime(2012, 2, 24, 14, 25, 46, 171000), datetime.datetime(2013, 2, 1, 14
, 25, 46, 171000), datetime.datetime(2013, 2, 8, 14, 25, 46, 171000), datetime.d
atetime(2013, 2, 15, 14, 25, 46, 171000), datetime.datetime(2013, 2, 22, 14, 25,
46, 171000)]
不要忘记查看datetime
模块的文档。