Recurring monthly events in Python

9 August 2008

I was working on something in one of my little Django sites and wondered how you make a recurring monthly event in Python? What I mean by recurring event is "every fourth Saturday" or "every first and second Wednesday" and so on.

I did not want to make a dependency on some huge calender server module like Calcore or Twisted's caldav. All I wanted was a function that accepts "every fourth Saturday" and returns me an actual date that I can use for scheduling things.

A quick google didn't come up with anything, so I decided to do it myself. Here are my first and second attempts. The first attempt just works it out mathematically, the second attempt uses a module from the Python standard library.

"""Helper for recurring date."""

DAYS = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
]

from datetime import date

def eventdate(year, month, target_day, target_ordinal):
    """Convert a human event date to a real date.
    For example, 'the third Thursday of the month'
    the target_ordinal is 3 and the target_day is 'Thursday'.
    """

    day = DAYS.index(target_day.title())

    match = 0
    for i in range(1, 32):
        try:
            if date(year, month, i).weekday() == day:
                match += 1
                if match == target_ordinal:
                    return date(year, month, i)

        except ValueError:
            return None

def main():
    """Example when called directly."""
    today = date.today()
    if today.month == 12:
        year = today.year + 1
        month = 1
    else:
        year = today.year
        month = today.month + 1
    print "Next Month's Linux group is", eventdate(year, month, 'Thursday', 3)
    print "Next Month's Python group is", eventdate(year, month, 'Saturday', 4)

# start the ball rolling
if __name__ == "__main__":
    main()

That worked quite fine, but like all good Python programmers, I want to be as efficient (/lazy) as possible, surely the standard library can do this for me? Well I found that the calendar module will return a matrix of dates organised by week and day. This works as follows:

"""Event helpers."""

def eventdate(year, month, target_day, target_ordinal):
    """Convert a human event date to a real date.
    For example, 'the third Thursday of the month'
    the target_ordinal is 3 and the target_day is 'Thursday'.
    """

    import calendar
    day = getattr(calendar, target_day.upper())
    cal = calendar.Calendar()
    return cal.monthdatescalendar(year, month)[target_ordinal - 1][day]

def main():
    """Example when called directly."""
    from datetime import date
    today = date.today()
    if today.month == 12:
        year = today.year + 1
        month = 1
    else:
        year = today.year
        month = today.month + 1
    print "Next Month's Linux group is", eventdate(year, month, 'Thursday', 3)
    print "Next Month's Python group is", eventdate(year, month, 'Saturday', 4)

# start the ball rolling

if __name__ == "__main__":
    main()

This seems to work identically as the above but in less lines of code. I still get the feeling I am trying too hard and I am missing something obvious, but maybe I am just being too much of perfectionist (as always).

If anyone knows or can work out a more efficient method, please do let me know.

1 Stavros says...

You should look at http://labix.org/python-dateutil, it does this and much more.

Posted at 7:14 p.m. on August 9, 2008


2 Tom Lynn says...

DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
        'Saturday']

def eventdate(year, month, target_day, target_ordinal):
    import sqlite3
    db = sqlite3.connect(':memory:')
    query = ("select date('%d-01-01', '%d months', '%d days', 'weekday %d');"
             % (year, month-1, 7*(target_ordinal-1), DAYS.index(target_day)))
    return db.execute(query).fetchone()[0]

Posted at 3:01 p.m. on September 24, 2008


3 Blg says...

I agree with all in this post! Thank you

Posted at 2:30 p.m. on February 19, 2009


4 Chris says...

If you put the following code before returning the value you can handle things like "the last Saturday" by using a negative target_ordinal. Also, it checks to see if the date that is being returned is a zero indicating that that day doesn't come until the next (or came in the previous) week:

if target_ordinal > 0 and weeks[target_ordinal - 1][day] == 0:
target_ordinal+=1
elif target_ordinal < 0 and weeks[target_ordinal][day] == 0:
target_ordinal-=1
if target_ordinal < 0:
target_ordinal += len(weeks) + 1

Posted at 12:44 p.m. on May 4, 2009


5 melissagibso says...

Hello,http://www.jumancuso.info - May i sex dating with you?

Posted at 4:34 p.m. on August 26, 2010


What do you have to say?

Show Editing Help

About

Hello, my name is Zeth, I'll be your host here.

Command Line Warriors is about taking control of your own technology, it looks at our experiences of computing; especially using GNU/Linux, the Python programming language, the command-line and issues such as techno-ethics, best practices and whatever is cool now. If you take control of your technology then you are a Warrior too!

This site is your site too which means that you can contribute and get involved. You can leave comments using the facility provided. For me, the comments and discussions are by far the best part of the site. So please do have your say!

Latest Discussions

Essex Web Design

September 3, 2010
A lot of contract providers give you free internet usage now, but if you have Pay As You Go, then you are going to be paying heavy prices.
Calling time on mobile internet nonsense?

Krasochka

September 2, 2010
Hack again?!
Adding more terminals to your function keys

GenryFlorist

September 2, 2010
<b>Cheap flowers delivery around the world!</b> Celebrate summer with our gorgeous flowers. They?re the perfect gift for any summer occasion. From birthdays to anniversaries, we offer beautiful flowers, lush plants, ...
Burning an iso to CD on Windows

auto-financing.co.cc

September 2, 2010
auto-financing
ReStructuredText tables and doctests

rubaxa

September 1, 2010
FTP = NOT RANDOM software Dominated hands postflop suckout often on all-ins. EX. AK vs. A9 or KQ vs. K6. Both players hit top pair. Bad player goes all in ...
Burning an iso to CD on Windows

empodayaddelm

September 1, 2010
Sorry admin - my post is test
This Week: Heroes and Monsters

increase synthroid dosage

September 1, 2010
Latest world news: 1 <a target="_blank" class="ext" href=http://www.maktabti.org/profiles/blogs/viagra-cialis-buy-no>buy cheap cialis generic levitra viagra</a> Viagra 2 <a target="_blank" class="ext" href=http://www.maktabti.org/profiles/blogs/buy-viagra-online-at-lowest>rainbowpush discussion board buy viagra</a> Viagra 3 <a target="_blank" class="ext" href=http://www.maktabti.org/profiles/blogs/how-to-get-generic-brand>search viagra ...
SFTP in Python: Paramiko

Lacilslaw

September 1, 2010
HYUN JAIMIE enniless and homele JAMILA
This Week: Heroes and Monsters

domaserisk

August 31, 2010
who was shaking his head back and forth knowingly Grissom shifted his eyes over at Brass,
How I Removed Windows from my Laptop

get ready loan

August 30, 2010
Though, by the you kill the legitimate PC user from visiting the site. Also, think about the dynamic IP's issue.
Only the penitent man will pass - on captchas and cotton wool

Packers and movers in pune

August 30, 2010
The topic you disscussed here is very amazing, informative and useful in future...
On Comment Spam

serhanters1

August 30, 2010
?? ???????? ??... ??????...... ??. ????????? ??? ??? ???????D ???????? ??. ????? ????? ???? ??? ???=) ?? ?????- http://letitbit.net/download/8746.894a84bc20f38f1661895aeee0/stereokartinki.html ???http://f-zona.ru ? ? ?? ????????????
Burning an iso to CD on Windows

strona startowa

August 29, 2010
Thanks For This Post, was added to my bookmarks.
Python CGI contact forms

lerexottori

August 29, 2010
?????????????? ??????????
Adding more terminals to your function keys

KelpAugmeme

August 29, 2010
aofaapsymp, http://forums.quark.com/members/jennaq.aspx online stock trading broker, rdgofzary
PuTTY Series: Adding PuTTY to your system path

Cheeday

August 28, 2010
What flowers do you like?
This Week: Heroes and Monsters

magfcvb

August 28, 2010
??????? ?????????????? ?????? - ????? ?????? ?????????????? ??????, ?????????????? ?????? ???????, ?????????????? ?????? crosman, ???? ??????????????? ??????, ?????????????? ?????? ?????? ????????. ???? magazin-oruzhie.ru
Include ODF support in the Linux Standard Base?

noni

August 28, 2010
I find myself coming to your blog more and more often to the point where my visits are almost daily now!
On Comment Spam

Latenadsfes

August 28, 2010
http://mynewblog.for-breastcancer.com/ http://mynewblog.photoblogcentral.com/ http://ilovezebras.thechicks.org/ http://mynewblog.cyberbardsymposium.com/ http://wewphost.com/ilovezebras/
Burning an iso to CD on Windows

LeupoldEst

August 28, 2010
pretty cool stuff here thank you!!!!!!!
OOXML Vote Coverage