Date Calculations

Derek Jones dtj at rincong.com
Sun Aug 29 00:02:14 EDT 1999


>I'm making some Date Calculaton class with things like
>deltaDays, addDays, daysInYear and so on, above the calendar 
>and time classes. After some 300 lines I thought, I better
>ask, whether that has already been done by someone else.
>How is this?

I am sure that the classes and libraries mentioned earlier in this thread
fit your bill more exactly.

However, for some simple, quick, classless date calculation, I have found
the standard 'time' module to be terrifically useful.  The big headache
(for me) with dates is handling things like a delta in days, or finding
out "what are all the dates of this week?", handling month rollover, leap
days, and other horrors.  The time.localtime and time.mktime functions are
really quite nice, and Python's tuple-unpacking makes the code quite
readable.  Attached as an example is a this_week() function that I needed
recently.  By always converting to and from the seconds-since-epoch that
the time module uses, date arithmetic becomes trivial.

--Derek

def this_week () :
    """
    Returns a list that includes every date this week, starting with
    Monday.
    """
    date_list = [ ]
    # We'll want all 5 weekdays for this week.
    for i in range (0, 5) :
        y, mo, d, h, m, s, wd, doy, dst = \
            time.localtime(time.time() - 86400*(weekday - i))
    date_str = "%2.2d/%2.2d/%4.4d" % (mo, d, y)
    date_list.append(date_str)
    return date_list

-- 
My real email address does not have a 'g' in it, for those who care.




More information about the Python-list mailing list