subtract dates with time module

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Mar 26 20:49:18 EDT 2008


En Wed, 26 Mar 2008 20:47:45 -0300, barronmo <barronmo at gmail.com> escribió:

> I'm trying to get the difference in dates using the time module rather
> than datetime because I need to use strptime() to convert a date and
> then find out how many weeks and days until that date.  I'm a beginner
> so any help would be appreciated.  Here is the code:
>
> def OBweeks(ptID):
>      qry = 'SELECT short_des FROM problems WHERE patient_ID = %s;'  %
> (ptID)
>      results = EMR_utilities.getAllData(qry)
>      for items in results:
>           r = re.search('\d\d\d\d-\d\d-\d\d', items)
>           if r:
>                d = time.strptime(r.group(), "%Y-%m-%d')  -
> time.localtime()
>                weeks, days  = divmod(d.days, 7)
>                return '%s %s/7 weeks'  % (weeks, days)
>
> This isn't working.  I'm getting "unsupported operand type for -:
> 'time.struct_time' and 'time.struct_time" error.

I don't see why you don't want to use datetime; it's the easiest way to  
compute the time difference.
To obtain the date object dt from the database, you might use the  
following, based on your posted code:

import datetime
match = re.search('(\d\d\d\d)-(\d\d)-(\d\d)', items)
if match:
     y, m, d = (int(x) for x in match.groups())
     dt = datetime.date(y, m, d)

Then, weeks and days are easily computed (similar to your own code):

now = datetime.date.today() # evaluate once outside the loop
delta = now - dt
weeks, days = divmod(delta.days, 7)

-- 
Gabriel Genellina




More information about the Python-list mailing list