"Sean" <nu*******@tfh.ca> writes:
I'm playing around times and dates. I'd like to determine the age of
particular sets of data in a user friendly matter.
I've got everything ready but dealing with time in a user friendly manner.
What would be a good way to express (in python):
time.localtime()+30 days
time.localtime()+5 minutes
time.localtime()+2 months
time.localtime()-2 years
Is there any python facilities to make this an easier chore (aka
time.localtime()+months(3))?
(I included months as it is a special case in that you can't just
arbitrarily calculate months in seconds without being relative to a
particular month).
mx.DateTime makes these sort of calculations easy. I have a similarish task
in presenting users an easy way of specifying which day's log files to search
(hence in this case it was always a date in the past but the principle would
be similar). So I allow things like 'monday', 'tuesday' etc. and -n for n
days ago and several other variations. The interesting one in this instance
is:
dm_reg = re.compile (r'^(-?\d\d?)[/.](-?\d\d?)$')
this_day = today()
# dd/mm (-ve dd means count from end of month, -mm is mm months ago)
mt = re.match (dm_reg, user_input)
if mt:
dy,mon = map(int, mt.groups())
if mon < 0:
mon = this_day.month + mon
if mon <= 0:
mon = 12 + mon
dt = DateTime (this_day.year, mon, dy)
if dt > this_day:
dt = DateTime (this_day.year-1, mon, dy)
return dt
Which allows eg 1/-2 for the first of whatever month was 2 months ago or even
-1/-1 for the last day of the previous month. mx.DateTime is doing all the
hard work. You could cook up something similar to parse eg "-2m" "+2y" etc.
Possibly the new time stuff in 2.3 will do this also, I haven't looked at 2.3
yet.
Eddie