Need Help comparing dates

Tim Chase python.list at tim.thechases.com
Fri Jun 16 03:29:09 CEST 2006


> I am new to Python and am working on my first program. I am trying to
> compare a date I found on a website to todays date. The problem I have
> is the website only shows 3 letter month name and the date.
> Example: Jun 15

No year, right?  Are you making the assumption that the year is 
the current year?

> How would I go about comparing that to a different date? 

Once you've got them as dates,

 >>> from datetime import date

you can just compare them as you would any other comparable items.

If you need to map the month-strings back into actual dates, you 
can use this dictionary:

 >>> month_numbers = dict([(date(2006, m, 1).strftime("%b"), m) 
for m in range(1,13)])

It happens to be locale specific, so you might have to tinker a 
bit if you're mapping comes out differently from what the website 
uses.  I also made the assumption the case was the same (rather 
than trying to normalize to upper/lower case)

Then, you can use

 >>> webpageDateString = "Mar 21"
 >>> webMonth, webDay = webpageDateString.split()
 >>> month = m[webMonth]
 >>> day = int(webDay)
 >>> webpageDate = date(date.today().year, month, day)
 >>> compareDate = date.today()
 >>> compareDate < webpageDate
False
 >>> compareDate > webpageDate
True

You can wrap the load in a function, something like

 >>> def isNewer(dateString, year = date.today().year):
...     monthString, dayString = dateString.split()
...     month = month_numbers[monthString]
...     day = int(dayString)
...     return date.today() < date(year, month, day)

which will allow you to do

 >>> isNewer("Jul 1")
True
 >>> isNewer("Apr 1")
False

and the like.

There's plenty of good stuff in the datetime module.

-tkc







More information about the Python-list mailing list