Needs programming tip using date

Alex Martelli aleax at aleax.it
Tue Aug 5 14:47:44 EDT 2003


Raaijmakers, Vincent (IndSys, GE Interlogix) wrote:

> I think this is a bit of a newbie question in the dates area.
> 
> So before I end up in very ugly coding,
> What is THE/recommended way in checking if a date formatted as
> "08/05/2003", so "month/day/year" is the date of today or a date of the
> current week?

If you don't want to install 3rd party extensions, such as the
excellent mxDateTime that's already been suggested to you, you
can also do it with tools from Python's own standard libraries
(in the current release, Python 2.3).

Considering a week as going from a Sunday (included) to the
following Saturday (included), i.e., with Sunday as the first
day of the week:

import time, datetime

def dateof(datestring):
    daytuple = time.strptime(datestring, '%m/%d/%y')[:3]
    return datetime.date(*daytuple)

offset = 0

def weekof(date):
    return (offset+date.toordinal()) // 7

this_week = weekof(date.today())


and now you can just test if this_week==weekof(whatever).


If you want to account for weeks differently (e.g. starting
from Monday) just set offset appropriately (e.g to -1).


Alex







More information about the Python-list mailing list