[Tutor] Working with dates

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Oct 17 08:23:29 CEST 2004



> > I am trying to write a function that will get today's date when run,
> > and set a string to the date of a day in the previous week.

> check out the mx.DateTime library at
> http://www.egenix.com/files/python/mxDateTime.html . In specific, look
> at the RelativeDate class; if you don't want to include this as a
> requirement in your software, look at how they code it.


Alternatively, we can use the DateTime class in the Standard Library:

    http://www.python.org/doc/lib/module-datetime.html

The classes there allow us to represent dates and time-difference
"deltas", and they should be perfect for this problem.  For example, here
is a function for figuring out when the next 8:00am will be:

###
def getTargetTime(hour=8, minute=00, second=0):
    """Returns the next upcoming datetime with the given hour, minute, or
    second.  The target datetime can be either today or tomorrow."""
    DAYDELTA = datetime.date.resolution
    currentTime = datetime.datetime.today()
    targetTime = currentTime.replace(hour=hour, minute=minute,
                                     second=second)
    if targetTime > currentTime:
        return targetTime
    else:
        return targetTime + DAYDELTA
###


It's part of a small "alarm clock" program that I wrote for myself...
*grin*  It should be useful for what Liam is trying to do.



Good luck!



More information about the Tutor mailing list