timesince.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # Copyright (c) Django Software Foundation and individual contributors.
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without modification,
  5. # are permitted provided that the following conditions are met:
  6. #
  7. # 1. Redistributions of source code must retain the above copyright notice,
  8. # this list of conditions and the following disclaimer.
  9. #
  10. # 2. Redistributions in binary form must reproduce the above copyright
  11. # notice, this list of conditions and the following disclaimer in the
  12. # documentation and/or other materials provided with the distribution.
  13. #
  14. # 3. Neither the name of Django nor the names of its contributors may be used
  15. # to endorse or promote products derived from this software without
  16. # specific prior written permission.
  17. #
  18. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  22. # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  25. # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. from __future__ import unicode_literals
  29. import datetime
  30. import pytz
  31. from mediagoblin.tools.translate import pass_to_ugettext, lazy_pass_to_ungettext as _
  32. def timesince(d, now=None, reversed=False):
  33. """
  34. Takes two datetime objects and returns the time between d and now
  35. as a nicely formatted string, e.g. "10 minutes". If d occurs after now,
  36. then "0 minutes" is returned.
  37. Units used are years, months, weeks, days, hours, and minutes.
  38. Seconds and microseconds are ignored. Up to two adjacent units will be
  39. displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are
  40. possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.
  41. Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
  42. """
  43. chunks = (
  44. (60 * 60 * 24 * 365, lambda n: _('year', 'years', n)),
  45. (60 * 60 * 24 * 30, lambda n: _('month', 'months', n)),
  46. (60 * 60 * 24 * 7, lambda n : _('week', 'weeks', n)),
  47. (60 * 60 * 24, lambda n : _('day', 'days', n)),
  48. (60 * 60, lambda n: _('hour', 'hours', n)),
  49. (60, lambda n: _('minute', 'minutes', n))
  50. )
  51. # Convert datetime.date to datetime.datetime for comparison.
  52. if not isinstance(d, datetime.datetime):
  53. d = datetime.datetime(d.year, d.month, d.day)
  54. if now and not isinstance(now, datetime.datetime):
  55. now = datetime.datetime(now.year, now.month, now.day)
  56. if not now:
  57. now = datetime.datetime.utcnow()
  58. delta = (d - now) if reversed else (now - d)
  59. # ignore microseconds
  60. since = delta.days * 24 * 60 * 60 + delta.seconds
  61. if since <= 0:
  62. # d is in the future compared to now, stop processing.
  63. return '0 ' + pass_to_ugettext('minutes')
  64. for i, (seconds, name) in enumerate(chunks):
  65. count = since // seconds
  66. if count != 0:
  67. break
  68. s = pass_to_ugettext('%(number)d %(type)s') % {'number': count, 'type': name(count)}
  69. if i + 1 < len(chunks):
  70. # Now get the second item
  71. seconds2, name2 = chunks[i + 1]
  72. count2 = (since - (seconds * count)) // seconds2
  73. if count2 != 0:
  74. s += pass_to_ugettext(', %(number)d %(type)s') % {'number': count2, 'type': name2(count2)}
  75. return s