Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating recurring dates using python?

Tags:

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).

like image 488
Nimmy Avatar asked Feb 19 '10 11:02

Nimmy


1 Answers

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']
like image 179
unutbu Avatar answered Oct 24 '22 14:10

unutbu