I'm sorry if this has been asked a thousand (million) times.Two options:
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()
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)
pyfrom datetime import datetime
pyd1 = datetime(1992, 5, 11, 8, 23, 8, 612)
pyd2 = datetime.now()
pyprint d1
1992-05-11 08:23:08.000612
pyprint d2
2008-05-08 09:21:53.592000
pyprint 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 offNope... 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.
into outer space (mentally!)
--
Gabriel Genellina