Writing elapsed time as a string

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu May 8 08:31:21 EDT 2008


En Fri, 02 May 2008 16:13:41 -0300, Simon Pickles <sipickles at googlemail.com> escribió:

> I'm sorry if this has been asked a thousand (million) times.
>
> Is there a nifty pythonesque way to produce a string representing an
> elapsed time period, in terms of years, months, days, hours, mins, seconds?
>
> I am storing times in a MySQL db, and would love to be able to write the
> time elapsed between accesses of certain data. These are in seconds
> since the epoch, as produced by time.time()

Two options:

a) You can construct a datetime object with that info, using datetime.datetime.fromtimestamp()
(note that the MySQLdb module already returns datetime objects for timestamp columns in MySQL).
If you substract two datetime objects, you get a timedelta object, which stores info as whole days, seconds (fraction of day) and microseconds (fraction of second). If you can live with years having exactly 365 days and months having exactly 30 days (or up to 35!):

def timedelta_str(td):
     def plural(n):
         if n>1: return 's'
         return ''
     out = []
     y, d = divmod(td.days, 365)
     if y: out.append('%d year' % y + plural(y))
     m, d = divmod(d, 30)
     if m: out.append('%d month' % m + plural(m))
     if d: out.append('%d day' % d + plural(d))
     h, s = divmod(td.seconds, 60*60)
     if h: out.append('%d hour' % h +  + plural(h))
     m, s = divmod(s, 60)
     if m: out.append('%d min' % m + plural(m))
     if s: out.append('%d sec' % s + plural(s))
     return ' '.join(out)

py> from datetime import datetime
py> d1 = datetime(1992, 5, 11, 8, 23, 8, 612)
py> d2 = datetime.now()
py> print d1
1992-05-11 08:23:08.000612
py> print d2
2008-05-08 09:21:53.592000
py> print timedelta_str(d2-d1)
16 years 1 day 58 mins 45 secs

or b) Use the dateutil package <http://labix.org/python-dateutil>

> It is probable right in front of me in the docs but I am spinning off
> into outer space (mentally!)

Nope... showing time intervals as years,months,days... isn't trivial, because there are many special cases, and sometimes legal issues too. It's impossible to make everyone happy in this topic.

-- 
Gabriel Genellina




More information about the Python-list mailing list