How to get first/last day of the previous month?

John Machin sjmachin at lexicon.net
Tue Jan 20 14:06:22 EST 2009


On Jan 21, 2:07 am, Marco Mariani <ma... at sferacarta.com> wrote:
> Carsten Haese wrote:
> > In order to not deprive you of the sense of accomplishment
>
> Sorry for spoiling that. If you still want the sense of accomplishment,
> try to reimplement dateutil (and rrule). It's not as easy as it seems :-o

True, but getting the last day of a given month from first principles
without any library routines is nowhere near as complex as (e.g.)
converting (y,m,d) <-> ordinal day number.

It's this easy:

# days in month (non-leap year)
_dim = (None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

def _leap(y):
    if y % 4: return 0
    if y % 100: return 1
    if y % 400: return 0
    return 1

def last_day_of_month(y, m):
    """Return day (1..31) which is last day of month m in year y
    """
    if m == 2:
        return 28 + _leap(y)
    if not (1 <= m <= 12):
        raise Exception("month not in 1..12")
    return _dim[m]

Cheers,
John



More information about the Python-list mailing list