Skip to content

Instantly share code, notes, and snippets.

@ninapavlich
Created February 22, 2018 02:46
Show Gist options
  • Save ninapavlich/415430cdfcea8a07a2669cbc3e269428 to your computer and use it in GitHub Desktop.
Save ninapavlich/415430cdfcea8a07a2669cbc3e269428 to your computer and use it in GitHub Desktop.
#Formats time differences in Python
def timesince(self, start=None, end=None, timesuffix='ago', instant_label='Just now'):
if not end:
end = timezone.now()
if not start:
start = self.start_time
dt = end - start
offset_seconds = dt.seconds + (dt.days * 60 * 60 * 24)
delta_s = int(round(offset_seconds % 60))
offset_minutes = offset_seconds / 60
delta_m = int(round(offset_minutes % 60))
offset_hours = offset_minutes / 60
delta_h = int(round(offset_hours % 24))
offset_days = offset_hours / 24
delta_d = int(round(offset_days % 7))
offset_weeks = offset_days / 7
delta_w = int(round(offset_weeks % 52))
offset_months = offset_days / 30
delta_n = int(round(offset_months % 12))
offset_years = offset_weeks / 52
delta_y = int(round(offset_years))
# More than two years, round to years
if delta_y > 1:
return u'%s years %s' % (delta_y, timesuffix)
if delta_y > 0:
return u'%s year %s' % (delta_y, timesuffix)
# Less than a year, but more than a month --> round to months
if delta_n > 1:
return u'%s months %s' % (delta_n, timesuffix)
if delta_n > 0:
return u'%s month %s' % (delta_n, timesuffix)
# Less than a month, but more than a week --> round to weeks
if delta_w > 1:
return u'%s weeks %s' % (delta_w, timesuffix)
if delta_w > 0:
return u'%s week %s' % (delta_w, timesuffix)
# Less than a week, but more than a day
if delta_d > 1:
return u'%s days %s' % (delta_d, timesuffix)
if delta_d > 0:
return u'%s day %s' % (delta_d, timesuffix)
# Less than a day, but more than an hour
if delta_h > 1:
return u'%s hours %s' % (delta_h, timesuffix)
if delta_h > 0:
return u'%s hour %s' % (delta_h, timesuffix)
# Less than an hour, but more than a minute
if delta_m > 1:
return u'%s minutes %s' % (delta_m, timesuffix)
if delta_m > 0:
return u'%s minute %s' % (delta_m, timesuffix)
# Less than an hour, but more than a minute
if delta_s > 1:
return u'%s seconds %s' % (delta_s, timesuffix)
return instant_label
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment