def duration(self): if self.current: return timesince(self.start) timediff = self.end - self.start if timediff.total_seconds() < 60: return '%0.0f seconds' % timediff.total_seconds() return timesince(timezone.now() - timediff)
def geosearch(request): place_name = request.GET.get("q", None) if not place_name: return JsonResponse({"status": "no query"}) center = geocode(place_name) if not center: return JsonResponse({"status": "no results"}) # geocode returns lat,lon but we store fields in lon,lat p = Point( center["coordinates"][1], center["coordinates"][0] ) try: d_m = max(100, min(3000, int(request.GET["d"]))) except (KeyError, ValueError): d_m = 1000 d = D(m=d_m) things = get_things_near_point( point=p, distance=d ) points = [ { "coordinates": [p.point.y, p.point.x], "title": p.title, "description": p.description, "timesince": _("%(since)s ago") % {"since": timesince(p.content_date)}, "link": p.content_object.get_absolute_url(), } for p in things["points"] ] polygons = [ { "coordinates": [ [[[y,x] for x,y in ring] for ring in poly] for poly in mp.polygon], "title": mp.title, "description": mp.description, "timesince": _("%(since)s ago") % {"since": timesince(p.content_date)}, "link": p.content_object.get_absolute_url(), } for mp in things["polygons"] ] return JsonResponse({ "status": "ok", "center": center, "points": points, "polygons": polygons, "radius": d.m })
def geosearch(request): place_name = request.GET.get("q", None) if not place_name: return JsonResponse({"status": "no query"}) center = geocode(place_name) if not center: return JsonResponse({"status": "no results"}) # geocode returns lat,lon but we store fields in lon,lat p = Point(center["coordinates"][1], center["coordinates"][0]) try: d_m = max(100, min(3000, int(request.GET["d"]))) except (KeyError, ValueError): d_m = 1000 d = D(m=d_m) things = get_things_near_point(point=p, distance=d) points = [{ "coordinates": [p.point.y, p.point.x], "title": p.title, "description": p.description, "timesince": _("%(since)s ago") % { "since": timesince(p.content_date) }, "link": p.content_object.get_absolute_url(), } for p in things["points"]] polygons = [{ "coordinates": [[[[y, x] for x, y in ring] for ring in poly] for poly in mp.polygon], "title": mp.title, "description": mp.description, "timesince": _("%(since)s ago") % { "since": timesince(p.content_date) }, "link": p.content_object.get_absolute_url(), } for mp in things["polygons"]] return JsonResponse({ "status": "ok", "center": center, "points": points, "polygons": polygons, "radius": d.m })
def _get_last_post_info(self): if self.last_post: params = ( self.last_post.date_created.strftime('%d %b %y at %H:%M:%S'), timesince(self.last_post.date_created), ) return mark_safe('<abbr title="Posted %s">%s</abbr>' % params)
def apps(): HEADING = 'Apps' PAGE_SIZE = 5 heading(HEADING) command("github.search('django')", wait=True) repositories = github.search('django')['repositories'] for index, repository in enumerate(repositories): updated = parse_datetime( repository['pushed_at']).replace(tzinfo=timezone.utc) age = (timezone.now() - updated) if age < datetime.timedelta(30*2): age_colour = 'green' elif age < datetime.timedelta(30*6): age_colour = 'blue' elif age < datetime.timedelta(365): age_colour = 'magenta' else: age_colour = 'red' comment( u'{0[username]}:{1} - {2} - {3}'.format( repository, coloured(coloured(repository['name'], 'bold'), 'black'), coloured(u'\u2605 {0[watchers]}'.format(repository), 'yellow'), coloured(timesince(updated), age_colour), ), coloured(truncatechars(repository['description'], 70), 'grey'), ) if index > 0 and index % PAGE_SIZE == 0: heading(HEADING)
def printable_metadata(self, html=True): ret = [] if self.type == 'user_activated': ret.append(_(u'by "%(username)s"') % {'username' : self.originator_user.username}) ret.append(' ') ret.append(_(u"%(time_since)s ago") % {'time_since':timesince(self.created)}) return ''.join(ret)
def get_expiration_date(self, obj): if not obj.expiration_date: return mark_safe('<span style="color:green">nunca expira</span>') if obj.expiration_date and obj.expiration_date <= datetime.now(): return mark_safe('<span style="color:orange">expiro hace %s</span>' % timesince(obj.expiration_date)) return mark_safe('<span style="color:green">expira en %s</span>' % timeuntil(obj.expiration_date))
def unread_messages(request): if not request.user.is_authenticated(): data = { 'unread_count':0, 'unread_list':[] } return JsonResponse(data) unread_list = [] messages = Message.objects.filter(recipient=request.user,read=False,deleted=False).order_by('date').reverse() for n in messages: struct = model_to_dict(n) if n.sender: struct['sender'] = str(n.sender) if n.recipient: struct['recipient'] = str(n.recipient) if n.date: struct['date'] = defaultfilters.timesince(n.date) if n.message: struct['message'] = str(n.message) struct['link'] = n.url() unread_list.append(struct) data = { 'unread_count': messages.count(), 'unread_list': unread_list } return JsonResponse(data)
def comment_dict(comment): return { 'id': str(comment.key().id()), 'user_fullname': comment.user_fullname(), 'body': comment.body, 'image_url':comment.image_url, 'ago': timesince(comment.created)}
def natural_time(value, time_range="86400"): """ For date and time values in time_range shows how many seconds, minutes or hours ago compared to current timestamp returns representing string. """ if not isinstance(value, datetime.date): # datetime is a subclass of date return value now = datetime.datetime.now() delta_time = now + datetime.timedelta(seconds=-int(time_range)) if value > delta_time and value < now: delta = now - value if delta.days != 0: return pgettext("naturaltime", "%(delta)s ago") % {"delta": defaultfilters.timesince(value)} elif delta.seconds == 0: return _(u"now") elif delta.seconds < 60: return ungettext(u"a second ago", u"%(count)s seconds ago", delta.seconds) % {"count": delta.seconds} elif delta.seconds // 60 < 60: count = delta.seconds // 60 return ungettext(u"a minute ago", u"%(count)s minutes ago", count) % {"count": count} else: count = delta.seconds // 60 // 60 return ungettext(u"an hour ago", u"%(count)s hours ago", count) % {"count": count} else: if value.year == now.year: return datetime.datetime.strftime(value, "%m月%d日 %H:%M") else: return datetime.datetime.strftime(value, "%Y年%m月%d日 %H:%M")
def timesince_short(value, arg=None): if not value: return '' try: return timesince(value, arg).split(",")[0] except (ValueError, TypeError): return
def naturaltime(value): """ For date and time values shows how many seconds, minutes or hours ago compared to current timestamp returns representing string. """ if not isinstance(value, date): # datetime is a subclass of date return value now = datetime.now(utc if is_aware(value) else None) if value < now: delta = now - value if delta.days != 0: return pgettext( 'naturaltime', '%(delta)s ago' ) % {'delta': defaultfilters.timesince(value, now)} elif delta.seconds == 0: return _('now') elif delta.seconds < 60: return ungettext( # Translators: \\u00a0 is non-breaking space 'a second ago', '%(count)s\u00a0seconds ago', delta.seconds ) % {'count': delta.seconds} elif delta.seconds // 60 < 60: count = delta.seconds // 60 return ungettext( # Translators: \\u00a0 is non-breaking space 'a minute ago', '%(count)s\u00a0minutes ago', count ) % {'count': count} else: count = delta.seconds // 60 // 60 return ungettext( # Translators: \\u00a0 is non-breaking space 'an hour ago', '%(count)s\u00a0hours ago', count ) % {'count': count} else: delta = value - now if delta.days != 0: return pgettext( 'naturaltime', '%(delta)s from now' ) % {'delta': defaultfilters.timeuntil(value, now)} elif delta.seconds == 0: return _('now') elif delta.seconds < 60: return ungettext( # Translators: \\u00a0 is non-breaking space 'a second from now', '%(count)s\u00a0seconds from now', delta.seconds ) % {'count': delta.seconds} elif delta.seconds // 60 < 60: count = delta.seconds // 60 return ungettext( # Translators: \\u00a0 is non-breaking space 'a minute from now', '%(count)s\u00a0minutes from now', count ) % {'count': count} else: count = delta.seconds // 60 // 60 return ungettext( # Translators: \\u00a0 is non-breaking space 'an hour from now', '%(count)s\u00a0hours from now', count ) % {'count': count}
def get_publication_date(self, obj): if obj.publication_date and obj.publication_date <= timezone.now(): return mark_safe( '<span style="color:green">publicado hace %s</span>' % timesince(obj.publication_date)) return mark_safe('<span style="color:blue">se publica en %s</span>' % timeuntil(obj.publication_date))
def comment_dict(comment): return { "id": str(comment.key().id()), "user_fullname": comment.user_fullname(), "body": comment.body, "image_url": comment.image_url, "ago": timesince(comment.created), }
def updates_dict(update): return { 'id':str(update.key().id()), 'user_fullname':update.user_fullname(), 'body':update.body, 'ago':timesince(update.created), 'image_url':update.image_url, 'comments':map(lambda c: comment_dict(c), update.comment_set) }
def render_data(self, obj): # If the datetime object is tz aware, conver it to local time datetime = getattr(obj, self.field_name) if is_aware(datetime): datetime = pytz.utc.normalize(datetime).\ astimezone(self.timezone) return _("%s ago") % timesince(getattr(obj, self.field_name))
def time_info(self): if self.previous_round and not self.start: return _('starts when %s is finished') % self.previous_round if self.is_not_yet_started(): return _('starts in %s') % timeuntil(self.start) if self.is_in_progress(): return _('ends in %s') % timeuntil(self.end) return _('ended %s ago') % timesince(self.end)
def _render(self): target = self.arg if target is None: target = utcnow() else: target = self.context[target] target = self._localize_datetime(self.tz, target) localized = self._localize_datetime(self.tz, self.datetime) return timesince(localized, target)
def updates_dict(update): return { "id": str(update.key().id()), "user_fullname": update.user_fullname(), "body": update.body, "ago": timesince(update.created), "image_url": update.image_url, "comments": map(lambda c: comment_dict(c), update.comment_set), }
def timeago (t, ) : return mark_safe( """<span class="datetime" data-datetime="%(datetime)s" data-since="%(since)s ago" ><span class="value">%(since)s ago</span></span>""" % dict( since=timesince(t, ), datetime=t, ), )
def age(value): now = datetime.datetime.now() try: difference = now - value except: return value if difference <= datetime.timedelta(minutes=1): return 'just now' return '%(time)s ago' % {'time': timesince(value).split(', ')[0]}
def ago(date_time): date_time = date_time.replace(tzinfo = None) diff = abs(date_time - datetime.today()) if diff.days <= 0: span = timesince(date_time) span = span.split(",")[0] # just the most significant digit if span == "0 " + _("minutes"): return _("seconds ago") return _("%s ago") % span return datetime.date(date_time)
def fuzzytime(value, fmt): delta = datetime.now() - value if delta < timedelta(hours=24): if delta < timedelta(minutes=1): return 'Just now' return timesince(value) + ' ago' return format(value, fmt)
def ago(date_time): date_time = date_time.replace(tzinfo=None) diff = abs(date_time - datetime.today()) if diff.days <= 0: span = timesince(date_time) span = span.split(",")[0] # just the most significant digit if span == "0 " + _("minutes"): return _("seconds ago") return _("%s ago") % span return datetime.date(date_time)
def printable_metadata(self, html=True): ret = [] if self.type == 'user_activated': ret.append( _(u'by "%(username)s"') % {'username': self.originator_user.username}) ret.append(' ') ret.append( _(u"%(time_since)s ago") % {'time_since': timesince(self.created)}) return ''.join(ret)
def get_expiration_date(self, obj): if not obj.expiration_date: return mark_safe('<span style="color:green">nunca expira</span>') if obj.expiration_date and obj.expiration_date <= timezone.now(): return mark_safe( '<span style="color:orange">expiro hace %s</span>' % timesince(obj.expiration_date)) return mark_safe('<span style="color:green">expira en %s</span>' % timeuntil(obj.expiration_date))
def get_review_details(r, request): res = { "id": r.id, "title": r.title, "comment": defaultfilters.linebreaksbr(r.comment), "ratio": int(r.rating) * 20, "user": {"icon": r.user.get_profile().get_icon_url()}, "own_review": r.user == request.user, "posted_by": "Posted %s ago by %s" % (defaultfilters.timesince(r.timestamp), r.user.username), } return res
def timesince_or_never(dt, default=None): """Call the Django ``timesince`` filter, but return the string *default* if *dt* is not a valid ``date`` or ``datetime`` object. When *default* is None, "Never" is returned. """ if default is None: default = _("Never") if isinstance(dt, datetime.date): return timesince(dt) else: return default
def timesince(value): from django.template.defaultfilters import timesince if not value: return 'Never' if value < datetime.datetime.now() - datetime.timedelta(days=5): return value.date() value = (' '.join(timesince(value).split(' ')[0:2])).strip(',') if value == '0 minutes': return 'Just now' if value == '1 day': return 'Yesterday' return value + ' ago'
def ago(date_time): diff = abs(date_time - datetime.utcnow().replace(tzinfo=pytz.utc)) if diff.days <= 0: span = timesince(date_time) span = span.split(",")[0] # just the most significant digit return "{} ago".format(span) else: if diff.days <= 1: label = 'day' else: label = 'days' return "{} {} ago".format(diff.days, label)
def timesince(value): from django.template.defaultfilters import timesince if not value: return _('Never') if value < now_with_tz_if_supported() - datetime.timedelta(days=5): return value.date() value = (' '.join(timesince(value).split(' ')[0:2])).strip(',') if value == _('0 minutes'): return _('Just now') if value == _('1 day'): return _('Yesterday') return value + _(' ago')
def serialize_accomplishments(accomplishments): data = [] for accomplishment in accomplishments: data.append({ 'id': accomplishment.id, 'type': accomplishment.content_type.name, 'station': accomplishment.station.title, 'inquiry': accomplishment.inquiry.title, 'content': accomplishment.content, 'created': timesince(accomplishment.created) }) return data
def timesince(value): from django.template.defaultfilters import timesince if not value: return _('Never') if value < timezone.now() - datetime.timedelta(days=5): return value.date() value = (' '.join(timesince(value).split(' ')[0:2])).strip(',') if value == _('0 minutes'): return _('Just now') if value == _('1 day'): return _('Yesterday') return value + _(' ago')
def microblogging_form(context, sender, starts_hidden=False, is_reply=False, reply_to='') : sender_class = ContentType.objects.get_for_model(sender) user = context['request'].user try : status = FeedItem.feed_manager.get_status(sender) status_since = defaultfilters.timesince(status.sent) status_text = status.short except FeedItem.DoesNotExist, e : status_since = '' status_text = ''
def repositories_commit_tree(request, repo, sha, path=None): commit = repo.get_commit(sha) if not commit: raise Http404 if not path or path[-1] == "/": if request.is_ajax() and "commits" in request.GET: tree = commit.get_tree(path, commits=True).tree tree_elements = [] for entry in tree: tree_elements.append( { "tree_id": entry["sha"], "id": entry["commit"].id, "author": entry["commit"].author, "commit_date": entry["commit"].commit_date, "since": timesince(entry["commit"].commit_date), } ) return HttpResponse(simplejson.dumps(tree_elements, cls=DjangoJSONEncoder), mimetype="application/json") tree = commit.get_tree(path) if tree is None: raise Http404 return render( request, "repositories/repository_tree.html", {"repository": repo, "commit": commit, "tree": tree, "breadcrumb": build_path_breadcrumb(path)}, ) else: file_obj = commit.get_file(path) if file_obj is None: raise Http404 file_blob_pygmentized = pygmentize(path.rsplit(".", 1)[-1], file_obj.content) return render( request, "repositories/repository_file.html", { "repository": repo, "commit": commit, "file_path": path, "file_obj": file_obj, "file_lines": range(1, file_obj.content.count("\n") + 1), "file_blob_pygmentized": file_blob_pygmentized, "breadcrumb": build_path_breadcrumb(path), }, )
def bettertimesince(dt): delta = datetime.datetime.utcnow() - dt local_dt = dt + datetime.timedelta(hours=UTC_OFFSET) if delta.days == 0: return timesince(dt) + " ago" elif delta.days == 1: return "Yesterday" + local_dt.strftime(" at %I:%M %p") elif delta.days < 5: return ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"][local_dt.weekday()] + local_dt.strftime(" at %I:%M %p") elif delta.days < 365: return local_dt.strftime("%B %d at %I:%M %p") else: return local_dt.strftime("%B %d, %Y")
def timesince(value): from django.template.defaultfilters import timesince now = utc_to_local(datetime.datetime.utcnow()) if not value: return _('never') if value < (now - datetime.timedelta(days=5)): return value.date() value = (' '.join(timesince(value, now).split(' ')[0:2])).strip(',') if value == _('0 minutes'): return _('just now') if value == _('1 day'): return _('yesterday') return value + _(' ago')
def timesince(value): from django.template.defaultfilters import timesince if not value: return "Never" if value < timezone.now() - timedelta(days=5): return value.date() value = (" ".join(timesince(value).split(" ")[0:2])).strip(",") if value == "0 minutes": return "Just now" if value == "1 day": return "Yesterday" return value + " ago"
def tree(request, repo, sha, path=None): try: commit = repo.get_commit(sha) except KeyError: raise Http404 if not path or path[-1] == '/': if request.is_ajax() and 'commits' in request.GET: tree = commit.get_tree(path, commits=True).tree tree_elements = [] for entry in tree: tree_elements.append({ 'tree_id': entry['sha'], 'id': entry['commit'].id, 'author': entry['commit'].author, 'commit_date': entry['commit'].commit_date, 'since': timesince(entry['commit'].commit_date), }) return HttpResponse(simplejson.dumps(tree_elements, cls=DjangoJSONEncoder), mimetype='application/json') try: tree = commit.get_tree(path) except KeyError: raise Http404 return render(request, 'trees/tree.html', { 'repository': repo, 'commit': commit, 'tree': tree, 'breadcrumb': build_path_breadcrumb(path) }) else: try: file_obj = commit.get_file(path) except KeyError: raise Http404 file_blob_pygmentized = pygmentize( path.rsplit('.', 1)[-1], file_obj.content) return render(request, 'trees/file.html', { 'repository': repo, 'commit': commit, 'file_path': path, 'file_obj': file_obj, 'file_lines': range(1, file_obj.content.count('\n') + 1), 'file_blob_pygmentized': file_blob_pygmentized, 'breadcrumb': build_path_breadcrumb(path) })
def string_for(cls, value): if not isinstance(value, date): # datetime is a subclass of date return value now = datetime.now(utc if is_aware(value) else None) if value < now: delta = now - value if delta.days != 0: # The only change being done is here and in the else clausule: # It splits the string returned by timesince filter and gets only first element # to shorten the string so e.g '1 days, 5 hours' becomes '1 days' return cls.time_strings['past-day'] % { 'delta': defaultfilters.timesince( value, now, time_strings=cls.past_substrings).split(',')[0], } elif delta.seconds == 0: return cls.time_strings['now'] elif delta.seconds < 60: return cls.time_strings['past-second'] % { 'count': delta.seconds } elif delta.seconds // 60 < 60: count = delta.seconds // 60 return cls.time_strings['past-minute'] % {'count': count} else: count = delta.seconds // 60 // 60 return cls.time_strings['past-hour'] % {'count': count} else: delta = value - now if delta.days != 0: return cls.time_strings['future-day'] % { 'delta': defaultfilters.timeuntil( value, now, time_strings=cls.future_substrings).split(',')[0], } elif delta.seconds == 0: return cls.time_strings['now'] elif delta.seconds < 60: return cls.time_strings['future-second'] % { 'count': delta.seconds } elif delta.seconds // 60 < 60: count = delta.seconds // 60 return cls.time_strings['future-minute'] % {'count': count} else: count = delta.seconds // 60 // 60 return cls.time_strings['future-hour'] % {'count': count}
def timesince(value, now=None): from django.template.defaultfilters import timesince if now is None: now = timezone.now() if not value: return _('never') if value < (now - timedelta(days=5)): return value.date() value = (' '.join(timesince(value, now).split(' ')[0:2])).strip(',') if value == _('0 minutes'): return _('just now') if value == _('1 day'): return _('yesterday') return value + _(' ago')
def repositories_commit_tree(request, repo, sha, path=None): commit = repo.get_commit(sha) if not commit: raise Http404 if not path or path[-1] == '/': if request.is_ajax() and 'commits' in request.GET: tree = commit.get_tree(path, commits=True).tree tree_elements = [] for entry in tree: tree_elements.append({ 'tree_id': entry['sha'], 'id': entry['commit'].id, 'author': entry['commit'].author, 'commit_date': entry['commit'].commit_date, 'since': timesince(entry['commit'].commit_date), }) return HttpResponse(simplejson.dumps(tree_elements, cls=DjangoJSONEncoder), mimetype='application/json') tree = commit.get_tree(path) if tree is None: raise Http404 return render(request, 'repositories/repository_tree.html', { 'repository': repo, 'commit': commit, 'tree': tree, 'breadcrumb': build_path_breadcrumb(path) }) else: file_obj = commit.get_file(path) if file_obj is None: raise Http404 file_blob_pygmentized = pygmentize( path.rsplit('.', 1)[-1], file_obj.content) return render(request, 'repositories/repository_file.html', { 'repository': repo, 'commit': commit, 'file_path': path, 'file_obj': file_obj, 'file_lines': range(1, file_obj.content.count('\n') + 1), 'file_blob_pygmentized': file_blob_pygmentized, 'breadcrumb': build_path_breadcrumb(path) })
def minute_to_duration(value): """ Display a human-readable reading-time (or any other duration) from a duration in minutes, with a granularity of 15 minutes. """ now = datetime.datetime.now() if value <= 0: return "" # Rounds value to avoid "1 hour, 2 minutes". if 55 <= value <= 65: value = 60 elif value > 65: value = value - (value % 15) delta = now - datetime.timedelta(minutes=value) return filters.timesince(delta).replace(", ", _(" et "))
def timesince(value, now=None): from django.template.defaultfilters import timesince if now is None: now = timezone.now() if not value: return _("never") if value < (now - timedelta(days=5)): return value.date() value = (" ".join(timesince(value, now).split(" ")[0:2])).strip(",") if value == _("0 minutes"): return _("just now") if value == _("1 day"): return _("yesterday") return _("%s ago") % value
def bettertimesince(dt): delta = datetime.datetime.utcnow() - dt local_dt = dt + datetime.timedelta(hours=UTC_OFFSET) if delta.days == 0: return timesince(dt) + " ago" elif delta.days == 1: return "Yesterday" + local_dt.strftime(" at %I:%M %p") elif delta.days < 5: return [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ][local_dt.weekday()] + local_dt.strftime(" at %I:%M %p") elif delta.days < 365: return local_dt.strftime("%B %d at %I:%M %p") else: return local_dt.strftime("%B %d, %Y")
def opiniones_guardar(request): if request.is_ajax(): opinion = Opiniones() opinion.opinion = request.GET['opinion'] opinion.save() o = ''' <div class="panel panel-default"> <div class="panel-body"> <strong>Anónimo</strong><br> {} <small style="color:#9A9999">hacé {}</small> </div> </div> '''.format(linebreaks(opinion.opinion), timesince(opinion.fecha_hora)) return JsonResponse({'opinion': o}) else: return HttpResponseRedirect(reverse('opiniones_cliente'))
def timetag_filter(value, arg=None): """Formats a date as a time since if less than 1 day old or as a date otherwise Will return <time...> html tag as part of the output. """ if not value: return value = _dt(value) arg = _dt(arg) if arg - value > timedelta(days=1): label = date(value, 'Y-m-d') else: label = timesince(value, arg) + " ago" return mark_safe("<time datetime=\"%s\" title=\"%s\">%s</time>" % (date(value, 'Y-m-d\TH:i:sO'), date(localtime(value), 'Y-m-d H:i:sO'), label))
def string_for(cls, value): if not isinstance(value, date): # datetime is a subclass of date return value now = datetime.now(utc if is_aware(value) else None) if value < now: delta = now - value if delta.days != 0: return cls.time_strings["past-day"] % { "delta": defaultfilters.timesince( value, now, time_strings=cls.past_substrings), } elif delta.seconds == 0: return cls.time_strings["now"] elif delta.seconds < 60: return cls.time_strings["past-second"] % { "count": delta.seconds } elif delta.seconds // 60 < 60: count = delta.seconds // 60 return cls.time_strings["past-minute"] % {"count": count} else: count = delta.seconds // 60 // 60 return cls.time_strings["past-hour"] % {"count": count} else: delta = value - now if delta.days != 0: return cls.time_strings["future-day"] % { "delta": defaultfilters.timeuntil( value, now, time_strings=cls.future_substrings), } elif delta.seconds == 0: return cls.time_strings["now"] elif delta.seconds < 60: return cls.time_strings["future-second"] % { "count": delta.seconds } elif delta.seconds // 60 < 60: count = delta.seconds // 60 return cls.time_strings["future-minute"] % {"count": count} else: count = delta.seconds // 60 // 60 return cls.time_strings["future-hour"] % {"count": count}
def string_for(cls, value): if not isinstance(value, date): # datetime is a subclass of date return value now = datetime.now(utc if is_aware(value) else None) if value < now: delta = now - value if delta.days != 0: return cls.time_strings['past-day'] % { 'delta': defaultfilters.timesince( value, now, time_strings=cls.past_substrings), } elif delta.seconds == 0: return cls.time_strings['now'] elif delta.seconds < 60: return cls.time_strings['past-templates'] % { 'count': delta.seconds } elif delta.seconds // 60 < 60: count = delta.seconds // 60 return cls.time_strings['past-minute'] % {'count': count} else: count = delta.seconds // 60 // 60 return cls.time_strings['past-hour'] % {'count': count} else: delta = value - now if delta.days != 0: return cls.time_strings['future-day'] % { 'delta': defaultfilters.timeuntil( value, now, time_strings=cls.future_substrings), } elif delta.seconds == 0: return cls.time_strings['now'] elif delta.seconds < 60: return cls.time_strings['future-templates'] % { 'count': delta.seconds } elif delta.seconds // 60 < 60: count = delta.seconds // 60 return cls.time_strings['future-minute'] % {'count': count} else: count = delta.seconds // 60 // 60 return cls.time_strings['future-hour'] % {'count': count}
def timesince(value): ''' Copied from django-sentry v1.6.2 github.com/dcramer/django-sentry ''' import datetime from django.template.defaultfilters import timesince if not value: return 'Never' if value < datetime.datetime.now() - datetime.timedelta(days=5): return value.date() value = (' '.join(timesince(value).split(' ')[0:2])).strip(',') if value == '0 minutes': return 'Just now' if value == '1 day': return 'Yesterday' return value + ' ago'
def check(request): return { 'hostname': socket.gethostname(), 'ips': ips, 'cpus': psutil.cpu_count(), 'uptime': timesince(datetime.fromtimestamp(psutil.boot_time())), 'memory': { 'total': filesizeformat(psutil.virtual_memory().total), 'available': filesizeformat(psutil.virtual_memory().available), 'used': filesizeformat(psutil.virtual_memory().used), 'free': filesizeformat(psutil.virtual_memory().free), 'percent': psutil.virtual_memory().percent }, 'swap': { 'total': filesizeformat(psutil.swap_memory().total), 'used': filesizeformat(psutil.swap_memory().used), 'free': filesizeformat(psutil.swap_memory().free), 'percent': psutil.swap_memory().percent } }
def timestr(value): # def distance_of_time(delta): # if delta < 1: # return 'less than a minute' # if delta == 1: # return '1 minute' # if delta < 50: # return '%s minutes' % delta # if delta < 90: # return 'about one hour' # if delta < 1080: # return '%s hours' % int(math.ceil(delta / 60)) # if delta < 1440: # return 'one day' # if delta < 2880: # return 'about one day' # days = int(math.ceil(delta / 1440)) # if days < 31: # return '%s days' % days # return 'about %s months' % int(math.ceil(days / 30)) if type(value) == type(""): value = datetime.datetime( *time.strptime(value, "%Y-%m-%d %H:%M:%S")[:6]) try: r = value - datetime.datetime.now() except TypeError: value = datetime.datetime( *time.strptime(value, "%Y-%m-%d %H:%M:%S")[:6]) r = value - datetime.datetime.now() delta = (r.days * 3600 * 24) + r.seconds # distance = distance_of_time(abs(int(delta / 60))) if delta > 0: return "in %s" % timeuntil(value) else: return "%s ago" % timesince(value)
def show_order_detail_view(request, pk): page_title = 'Заказ' order_items = OrderItem.objects.filter(order_id=pk).select_related('order') if order_items: order = order_items.first().order else: order = Order.objects.get(order_id=pk) form = OrderDetailModelForm() since_time = "{} назад".format(timesince(order.created_date, time_strings=ru_time_strings)) if request.method == 'POST': form = OrderDetailModelForm(data=request.POST) if form.is_valid(): form.save() else: form = OrderDetailModelForm() return render(request, 'order/order_detail.html', { 'form': form, 'order': order, 'sincetime': since_time, 'order_items': order_items, 'page_title': page_title, 'active_tab': active_tab})