Caculate age

Laura Creighton lac at strakt.com
Tue Feb 4 05:58:43 EST 2003


> --0-1922495227-1044348754=:27247
> Content-Type: text/plain; charset=us-ascii
> 
> 
> Here is what I have done so far :
> # This function calculates the age of a person based on a birthdate
> # For example: cal_age('02/01/1970')
> # Enter any birthdate in the format MM/DD/YYYY or MM-DD-YYYY
> # Uses mx.DateTime interface from www.lemburg.com
> import time
> import re
> from mx.DateTime import *
> def cal_age(text):
>  
>  m = re.match("(\d{1,2})/(\d{1,2})/(\d{1,4})",text)
>  n = re.match("(\d{1,2})-(\d{1,2})-(\d{1,4})",text)
>  if m:
>   mm = int(m.group(1))
>   dd = int(m.group(2))
>   yy = int(m.group(3))
>   diff = Age(now(),Date(yy,mm,dd))
>   print 'Your age: Years ',diff.years,'Months',diff.months,' Days',diff.days
>  if n:
>   mm = int(n.group(1))
>   dd = int(n.group(2))
>   yy = int(n.group(3))
>   diff = Age(now(),Date(yy,mm,dd))
>   print 'Your age: Years ',diff.years,'Months',diff.months,' Days',diff.days
>  
> Any comments or advise !
> How can I make it accept any format (YYYY-MM-DD etc..)
> By the way - This is not an assignment from a school or university class.
> --Thanks !

well, if it is not an assignment, mx.DateTime.DateFrom is the way to
go.  But if it is, see my first note about getting things 100% correct
and still a bad mark?  As a teacher, I would feel that I was grading
Marc-Andre Lemburg, who isn't registered for my course. 

By the way, you don't want to get into the habit of writing:

from <some library> import *

You don't want to ask for all the stuff that a module writer has
written, only those bits that you want.  Some sad day the module
writer and you will have picked the same names for things, and your
code will stop working because it is no longer doing what you asked it
to, but something else named the same in the module.  This is called
namespace pollution.  Avoid it.

Most people will like your code more if you indent by more than 1 space.

Laura





More information about the Python-list mailing list