Comparing dates problem
Tim Golden
mail at timgolden.me.uk
Thu May 10 03:37:43 EDT 2007
kyosohma at gmail.com wrote:
> I am writing a reminder program for our Zimbra email client. One of
> the requirements I was given was to automatically increment or
> decrement the display to show something like the following:
>
> 5 minutes until appointment
>
> or
>
> 10 minutes past your appointment
>
>
> Either way, as each minute goes by, I need to increment it or
> decrement it. I am having trouble finding a coherent way to take the
> same date and compare just the number of minutes between them to find
> the difference. Like if I have an appointment at 9:30 a.m. and the app
> is loaded at 8 a.m., I need to know the number of minutes or hours and
> minutes until the appointment.
Not the most elegant piece of code on earth,
but this piece of code works for me (cut-and-pasted
directly from a working project, so doesn't
*exactly* match your requirement).
<code>
def deltastamp (now, then):
def pluralise (base, n):
if n > 1:
return "%d %ss" % (n, base)
else:
return "%d %s" % (n, base)
if now > then:
output_format = "%s ago"
delta = now - then
else:
output_format = "in %s"
delta = then - now
days = delta.days
if days <> 0:
wks, days = divmod (days, 7)
if wks > 0:
output = pluralise ("wk", wks)
else:
output = pluralise ("day", days)
else:
mins, secs = divmod (delta.seconds, 60)
hrs, mins = divmod (mins, 60)
if hrs > 0:
output = pluralise ("hr", hrs)
elif mins > 0:
output = pluralise ("min", mins)
else:
output = pluralise ("sec", secs)
return output_format % output
</code>
TJG
More information about the Python-list
mailing list