Rcjp's Weblog

August 4, 2005

Parse Dates

Filed under: python — rcjp @ 7:32 pm

There is most likely a better default python module for this, but it is only a few lines to write anyhow…

from string import split

def parse_date(s):
    """Returns the numerical date e.g. (16,8,1980) given '16 aug 1980'"""

    monthnames = ['jan','feb','mar','apr','may','jun',

    months = dict([(month,i+1) for i, month in enumerate(monthnames)])
    # note! s.split(' ', 3) is not equivalent because of double spaces
    day, month, year = s.split(None, 3)
    return int(day), months[month.lower()], int(year)

print parse_date('16 aug 1980')


Leave a Comment »

No comments yet.

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: