使用python生成定期日期? [英] Generating recurring dates using python?

查看:113
本文介绍了使用python生成定期日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Python生成定期日期?例如,我想为第二个月的第三个星期五生成经常性的日期。我想生成每日,每周,每月,每年(即与Outlook Express中的重复函数相同)的定期日期。

解决方案

pre> import dateutil.rrule as dr
import dateutil.parser as dp
import dateutil.relativedelta as drel

start = dp.parse (19/02/2010)#2010年2月第三个星期五

这将产生第三个星期五每月

  rr = dr.rrule(dr.MONTHLY,byweekday = drel.FR(3),dtstart = start,count = 10)

每周三打印一次:

 打印地图(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是一个可迭代的,所以你可以使用切片符号来挑选每一个其他项目。这打印每隔一个月的第三个星期五:

 打印地图(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 [ rr [:: 2]中的d.strftime('%d /%m /%Y')
#['19 / 02/2010','16/04/2010','18 / 06/2010','20 / 08/2010','15 / 10/2010']


How can I generate recurring dates using Python? For example I want to generate recurring date for "Third Friday of every second month". I want to generate recurring dates for daily, weekly, monthly, yearly (i.e., same as the recurrence function in Outlook Express).

解决方案

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

This generates the third Friday of every month

rr = dr.rrule(dr.MONTHLY,byweekday=drel.FR(3),dtstart=start, count=10)

This prints every third Friday:

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 is an iterable, so you can use slicing notation to pick out every other item. This prints the third Friday of every other month:

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']

Above, I used str to prettify the output a little bit. For more flexible string formatting of dates, use strftime: See http://au2.php.net/strftime or the man page for strftime for all the options.

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']

这篇关于使用python生成定期日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆