def timesince(value, arg=None): if value is None or isinstance(value, Undefined): return u'' from django.utils.timesince import timesince if arg: return timesince(value, arg) return timesince(value)
def __unicode__(self): if self.object_c_obj and self.target_c_obj: return u'%s %s %s on %s %s ago' % ( self.actor_c_obj, self.verb, self.object_c_obj, self.target_c_obj, timesince(self.published) ) elif self.object_c_obj: return u'%s %s %s %s ago' % ( self.actor_c_obj, self.verb, self.object_c_obj, timesince(self.published) ) elif self.target_c_obj: return u'%s %s on %s %s ago' % ( self.actor_c_obj, self.verb, self.target_c_obj, timesince(self.published) ) else: return u'%s %s %s ago' % ( self.actor_c_obj, self.verb, timesince(self.published) )
def get_title(self): """ Returns a human-readable title for this order, based on various criteria """ from django.utils.timesince import timesince now = timezone.now() moment_seconds = 120 if self.closed_at: if (now - self.closed_at).seconds < moment_seconds: return _("Closed a moment ago") return _(u"Closed for %(time)s") % {'time': timesince(self.closed_at)} if self.status and self.status_started_at is not None: if (now - self.status_started_at).seconds < moment_seconds: return _(u"%s a moment ago") % self.status.status.title delta = timesince(self.status_started_at) d = {'status': self.status.status.title, 'time': delta} return _("%(status)s for %(time)s" % d) if self.user is None: if (now - self.created_at).seconds < moment_seconds: return _("Created a moment ago") return _("Unassigned for %(delta)s") % {'delta': timesince(self.created_at)} if self.in_progress(): if (now - self.started_at).seconds < moment_seconds: return _("Started a moment ago") return _("Open for %(delta)s") % {'delta': timesince(self.started_at)}
def timesince(value, arg=None): """Formats a date as the time since that date (i.e. "4 days, 6 hours").""" from django.utils.timesince import timesince if not value: return u'' if arg: return timesince(value, arg) return timesince(value)
def ltimesince(value, arg=None): 'Formats a date as the time since that date (i.e. "4 days, 6 hours")' from django.utils.timesince import timesince if not value: return '' if arg: return timesince(arg, value) return timesince(value)
def get_prod_data(self): def get_months_until_stockout_icon(value): stock_levels = CommtrackConfig.for_domain(self.config['domain']).stock_levels_config if float(value) == 0.0: return '%s <span class="icon-remove" style="color:red"/>' % value elif float(value) < stock_levels.understock_threshold: return '%s <span class="icon-warning-sign" style="color:orange"/>' % value elif stock_levels.understock_threshold < float(value) < stock_levels.overstock_threshold: return '%s <span class="icon-ok" style="color:green"/>' % value elif float(value) >= stock_levels.overstock_threshold: return '%s <span class="icon-arrow-up" style="color:purple"/>' % value state_grouping = {} loc = SQLLocation.objects.get(location_id=self.config['location_id']) stock_states = StockState.objects.filter( case_id=loc.supply_point_id, section_id=STOCK_SECTION_TYPE, sql_product__in=self.unique_products([loc]) ).order_by('-last_modified_date') for state in stock_states: monthly_consumption = int(state.get_monthly_consumption()) if state.get_monthly_consumption() else 0 if state.product_id not in state_grouping: state_grouping[state.product_id] = { 'commodity': state.sql_product.name, 'months_until_stockout': "%.2f" % (state.stock_on_hand / monthly_consumption) if state.stock_on_hand and monthly_consumption else 0, 'stockout_duration': timesince(state.last_modified_date) if state.stock_on_hand == 0 else '', 'stockout_duration_helper': state.stock_on_hand == 0, 'current_stock': state.stock_on_hand, 'monthly_consumption': monthly_consumption, 'reorder_level': int(monthly_consumption * REORDER_LEVEL), 'maximum_level': int(monthly_consumption * MAXIMUM_LEVEL), 'date_of_last_report': state.last_modified_date.strftime("%Y-%m-%d") } elif state_grouping[state.product_id]['stockout_duration_helper']: if not state.stock_on_hand: state_grouping[state.product_id]['stockout_duration'] = timesince(state.last_modified_date) else: state_grouping[state.product_id]['stockout_duration_helper'] = False for values in state_grouping.values(): yield { 'commodity': values['commodity'], 'current_stock': int(values['current_stock']), 'monthly_consumption': values['monthly_consumption'] if values['monthly_consumption'] != 0.00 else 'not enough data', 'months_until_stockout': get_months_until_stockout_icon(values['months_until_stockout'] if values['months_until_stockout'] else 0.0), 'stockout_duration': values['stockout_duration'], 'date_of_last_report': values['date_of_last_report'], 'reorder_level': values['reorder_level'] if values['reorder_level'] != 0.00 else 'unknown', 'maximum_level': values['maximum_level'] if values['maximum_level'] != 0.00 else 'unknown'}
def index(request): log = logging.getLogger(__name__) context = {} packed_values = api.get_like_data_through_cache() if packed_values == "error": return render(request, 'istayon/index.html', get_error_context()) count, last_liked, histogram, bins = packed_values imstillinbeta_avatar, strangelookonhisface_avatar = api.get_avatar_urls() if histogram: # ramp up if histogram[-1] > 0 and histogram[-2] == 0: message = MESSAGE_FORMAT_STRING.format(phrases.get_maybe(), phrases.get_name(), phrases.get_maybe_up_end()) context['title'] = "IsTayOnTumblr?" # ramp down elif histogram[-1] == 0 and histogram[-2] > 0: message = MESSAGE_FORMAT_STRING.format(phrases.get_maybe(), phrases.get_name(), phrases.get_maybe_down_end()) context['title'] = "IsTayOnTumblr?" # online elif (histogram[-1] > 0 and histogram[-2] > 0) or sum(histogram[-2:]) > 5: message = MESSAGE_FORMAT_STRING.format(phrases.get_yes(), phrases.get_name(), phrases.get_yes_end()) context['title'] = "IsTayOnTumblr?" # offline elif sum(histogram[-2:]) == 0: message = MESSAGE_FORMAT_STRING.format(phrases.get_no(), phrases.get_name(), phrases.get_no_end()) context['title'] = "IsTayOnTumblr?" # offline else: message = MESSAGE_FORMAT_STRING.format(phrases.get_no(), phrases.get_name(), phrases.get_no_end()) context['title'] = "No - IsTayOnTumblr?" if histogram: # I just put the data on the forward edge of the bin, so ignore the first bin edge. # at some point maybe I should center it on the bin, but this worked for now. context['plot_data'] = map(list, zip(bins[1:], histogram)) xticks = [] now_unix = bins[-1] start_unix = now_unix - (settings.HOURS_BACK * 60 * 60) tick_width = 60 / TICK_INTERVAL_MINUTES # define the tick locations on the plot # basically, make a list of lists, where each sublist is [tick location, tick text] # and if it's not on an hour, then just use an empty string for the text for i in xrange(settings.HOURS_BACK * 60 / TICK_INTERVAL_MINUTES + 1): xticks.append([start_unix + i * 60 * TICK_INTERVAL_MINUTES, settings.HOURS_BACK-(i/tick_width) if i % tick_width == 0 else ""]) context['xmin'] = start_unix context['xticks'] = json.dumps(xticks) context['message'] = message context['count'] = count # reduce specificity if it's been over six hours since she liked something. context['last_liked'] = u"It's been {0} since she liked something.".format( timesince(last_liked, timezone.now()) if (timezone.now() - last_liked < timedelta(hours=6)) else "about " + timesince(last_liked, timezone.now()).split(',')[0]) context['isib'] = imstillinbeta_avatar context['slohf'] = strangelookonhisface_avatar return render(request, 'istayon/index.html', context)
def test_different_timezones(self): """ When using two different timezones. """ now = datetime.datetime.now() now_tz = datetime.datetime.now(LocalTimezone(now)) now_tz_i = datetime.datetime.now(FixedOffset((3 * 60) + 15)) self.assertEquals(timesince(now), u'0 minutes') self.assertEquals(timesince(now_tz), u'0 minutes') self.assertEquals(timeuntil(now_tz, now_tz_i), u'0 minutes')
def timeuntil(value, arg=None): """Formats a date as the time until that date (i.e. "4 days, 6 hours").""" from django.utils.timesince import timesince from datetime import datetime if not value: return '' if arg: return timesince(arg, value) return timesince(datetime.now(), value)
def timedelta(value): if not value: return '' now = datetime.utcnow().replace(tzinfo=utc) if value > now: return _("in %s") % timesince(now, value) else: return timesince(value, now)
def test_different_timezones(self): """ When using two different timezones. """ now = datetime.datetime.now() now_tz = timezone.make_aware(now, timezone.get_default_timezone()) now_tz_i = timezone.localtime(now_tz, timezone.get_fixed_timezone(195)) self.assertEqual(timesince(now), "0\xa0minutes") self.assertEqual(timesince(now_tz), "0\xa0minutes") self.assertEqual(timeuntil(now_tz, now_tz_i), "0\xa0minutes")
def test_display_first_unit(self): """ If the two differing units aren't adjacent, only the first unit is displayed. """ self.assertEqual( timesince(self.t, self.t + 2 * self.oneweek + 3 * self.onehour + 4 * self.oneminute), '2\xa0weeks' ) self.assertEqual(timesince(self.t, self.t + 4 * self.oneday + 5 * self.oneminute), '4\xa0days')
def timesince_filter(value, arg=None): """Format a date as the time since that date (i.e. "4 days, 6 hours").""" if not value: return '' try: if arg: return timesince(value, arg) return timesince(value) except (ValueError, TypeError): return ''
def timesince(value, arg=None): """Formats a date as the time since that date (i.e. "4 days, 6 hours").""" from django.utils.timesince import timesince if not value: return '' try: if arg: return timesince(value, arg) return timesince(value) except (ValueError, TypeError): return ''
def get_due_display(self): from django.utils.timesince import timesince import datetime now = datetime.datetime.now() if not self.due: return u'' if self.due <= now: #d = timesince(self.due, now) return u'%s ago' % timesince(self.due, now) else: return u'in %s' % timesince(now, self.due)
def simpletimesince(value, arg=None): """Formats a date as the time since that date (i.e. "4 days, 6 hours").""" from django.utils.timesince import timesince if not value: return u'' try: if arg: return timesince(value, arg) return timesince(value, datetime.datetime.utcnow()).split(', ')[0] except (ValueError, TypeError): return u''
def timedelta(value, arg=None): if not value: return '' if arg: cmp = arg else: cmp = djtz.now() if value > cmp: return u"还有%s" % timesince(cmp,value) else: return u"%s之前" % timesince(value,cmp)
def timedelta (value, arg=None): if not value: return '' if arg: cmp = arg else: cmp = datetime.now() if value > cmp: return "%s" % timesince(cmp,value) else: return "%s" % timesince(value,cmp)
def timedelta(value_timestamp, arg=None): if not value_timestamp: return '' value = datetime.utcfromtimestamp(value_timestamp) if arg: cmp = datetime.utcfromtimestamp(arg) else: cmp = datetime.utcnow() if value > cmp: msg = "in %s" % timesince(cmp,value) else: msg = "%s ago" % timesince(value,cmp) return msg
def timedelta(value, arg=None): if not value: return '' if arg: cmp = arg else: cmp = datetime.now() if settings.USE_TZ: cmp = make_aware(cmp, get_default_timezone()) if value > cmp: return "in %s" % timesince(cmp, value) else: return "%s ago" % timesince(value, cmp)
def short_timesince(date): """ A shorter version of Django's built-in timesince filter. Selects only the first part of the returned string, splitting on the comma. Falls back on default Django timesince if it fails. Example: 3 days, 20 hours becomes "3 days". """ try: return timesince(date).split(", ")[0] except IndexError(): timesince(date)
def timeago(value, arg=None): """Formats a date as the time since that date ("2 hours ago").""" if not value: return u'' try: if arg: return timesince(value, arg) timeagoval = timesince(value).split(",")[0] if timeagoval == "0 minutes": return "just now" else: return "%s ago" % timeagoval except (ValueError, TypeError): return u''
def _get_errors(self): """ Fetches the overdue jobs from ipdevpolljoblog. Because some jobs will take some time to run, give some slack to what is considered overdue. """ slack = 120 # Seconds query = """ SELECT ijl.* FROM ipdevpoll_job_log AS ijl JOIN ( SELECT netboxid, job_name, MAX(end_time) AS end_time FROM ipdevpoll_job_log GROUP BY netboxid, job_name ) AS foo USING (netboxid, job_name, end_time) JOIN netbox ON (ijl.netboxid = netbox.netboxid) WHERE now() - interval '1 second' * interval > end_time ORDER BY netboxid; """ errors = [] for job in IpdevpollJobLog.objects.raw(query): should_have_run = job.end_time + timedelta(seconds=job.interval) overdue_by = datetime.now() - should_have_run if overdue_by.seconds > slack and job.netbox.is_up(): time_since = timesince(datetime.now() - overdue_by) descr = "Job {} on {} is overdue by {}".format( job.job_name, job.netbox.sysname, time_since) errors.append(TestResult(descr, job)) return errors
def _generate_notification_response(notification, next_page): """ Converts a notification into a Python dictionary that will be returned as JSON. notification: Notification object """ response = { 'user_name': notification.sender.get_full_name(), 'user_url': reverse('user-profile', args=[notification.sender_id]), 'user_avatar': notification.sender.userprofile.thumbnail.url, 'message': MESSAGES[notification.notification_type], 'time_since': timesince(notification.created_at), 'next': next_page } if (notification.notification_type == "thank" or notification.notification_type == "agree"): item_type = notification.item.item_type response['item_name'] = getattr(notification.item, item_type).__str__() response['item_url'] = reverse(item_type+'-profile', args=[slugify(response['item_name'])]) if notification.notification_type == "thank": response['thank_you'] = escape(notification.note) return response
def timesince_threshold(value, hours=1): if datetime.utcnow() - value.replace(tzinfo=None) < timedelta(hours=hours): return str(timesince(value)) + " ago" else: return formats.date_format(value, "DATE_FORMAT") #return value|date:"d M, Y" timesince_threshold.is_safe = False
def time_since_submitted(self): """ Human-readable formatting of interval since submitted. """ return mark_safe('<li>%s</li>' % ( capfirst(_("submitted %(interval)s ago")) % {'interval': timesince(self.submitted)}))
def sysinfo(self, command): """ Shows system/bot information """ process = psutil.Process(os.getpid()) mem_usage = process.memory_info().rss created = datetime.datetime.fromtimestamp(int(process.create_time())) repo = Repo(settings.PROJECT_ROOT) msg = ( "Uptime: `{uptime}`\n" "Memory usage: `{mem}`\n" "OS: `{system}, {release}`\n" "Current branch: `{branch}`, `{commit}`, \n`{message}`\n" ).format( mem=filesizeformat(mem_usage), uptime=timesince(created), system=platform.system(), release=platform.release(), branch=repo.active_branch.name, commit=repo.active_branch.commit.hexsha, message=repo.active_branch.commit.message, ) yield from command.reply(msg)
def get_timesince(self): delta = (now() - self.created) if delta.days <= 1: return '{0} ago'.format(timesince(self.created, now())) if self.created.year != now().year: return date(self.created, 'd F Y') return date(self.created, 'd F')
def last_seen(value, autoescape=None): """Formats a datetime as an HTML string representing a short digest of the time since that date, contained by a <span>, with a title (tooltip) of the full date.""" # if autoescaping is on, then we will # need to pass outgoing strings through # cond_esc, or django will escape the HTML if autoescape: esc = conditional_escape else: esc = lambda x: x try: if value: # looks like we have a valid date - return # a span containing the long and short version ts = timesince(value) mag = magnitude_ago(value) long = "on %s at %s" % (filter_date(value), filter_time(value)) out = '<span class="last-seen %s" title="%s">%s ago</span>' % (esc(mag), esc(long), esc(ts)) # abort if there is no date (it's # probably just a null model field) else: out = '<span class="last-seen n/a">Never</span>' # something went wrong! don't blow up # the entire template, just flag it except (ValueError, TypeError): out = '<span class="last-seen error">Error</span>' return mark_safe(out)
def get_recent_notifications(user_id): """ Returns the last five notifications for a user. user_id: primary key of the user (integer) """ raw_notifications = cacheAPI._get_notifications(user_id) response = [{ 'user_name': notification['sender_name'], 'user_url': reverse('user-profile', args=[notification['sender_id']]), 'user_avatar': get_thumbnail( 'img/users/thumbnails/' + \ str(notification['sender_id']) + 't.jpg', '25x25', crop='center' ).url, 'message': MESSAGES[notification['notification_type']], 'item_name': notification.get('item_name', ''), 'item_url': (reverse(notification['item_type']+'-profile', args=[slugify(notification.get('item_name', 'none'))]) if notification.get('item_type') else ''), 'time_since': timesince(notification['timestamp']) } for notification in raw_notifications] return simplejson.dumps(response)
def age(self): return "{t} ago".format(t=timesince(self.timestamp))
def test_date_objects(self): """ Both timesince and timeuntil should work on date objects (#17937). """ today = datetime.date.today() self.assertEqual(timesince(today + self.oneday), '0\xa0minutes') self.assertEqual(timeuntil(today - self.oneday), '0\xa0minutes')
def publish_date_since(self): """ Returns the time since ``publish_date``. """ return timesince(self.publish_date)
def get_time_since_publication(self, object): publication_date = object.publication_date now = datetime.now() time_delta = timesince(publication_date, now) return time_delta
def utctimesince(value): if not value: return "" return timesince(value, now=datetime.utcnow())
def get_timesince(self, obj): return timesince(obj.timestamp) + " ago"
def get_timesince_posted(self, obj): return timesince(obj.date_created)
def logged(self, obj): if obj.last_log is None: return '-' return timesince(obj.last_log) + ' ago'
def test_leap_year_new_years_eve(self): t = datetime.date(2016, 12, 31) now = datetime.datetime(2016, 12, 31, 18, 0, 0) self.assertEqual(timesince(t + self.oneday, now), '0\xa0minutes') self.assertEqual(timeuntil(t - self.oneday, now), '0\xa0minutes')
def time_since(strval): """Time interval.""" try: return timesince(strval) except: return strval
def pester(dry_run=False, force_run=False): # because some users potentially belong to multiple groups # we need to make a map of each users' events to be # pestered about users = collections.defaultdict(list) # we only want to bother with approvals of events that are # of a minimum age now = datetime.datetime.utcnow().replace(tzinfo=utc, microsecond=0) minimum_created_date = now - datetime.timedelta(seconds=INTERVAL) approvals = ( Approval.objects.filter( processed=False, event__created__lt=minimum_created_date).exclude( event__status=Event.STATUS_REMOVED).select_related( 'event', 'group').order_by('event__created') # oldest first ??? ) for approval in approvals: # exclude those with no email users_qs = (approval.group.user_set.filter(is_active=True).exclude( email='')) for user in users_qs: cache_key = 'pestered-%s-%s' % (user.pk, approval.pk) if not cache.get(cache_key) or force_run: users[user].append(approval) approval_texts = {} emails_sent = [] for user, approvals in users.items(): texts = [] cache_keys = [] for approval in approvals: if approval not in approval_texts: if approval.event.start_time > now: time_left = timesince(approval.event.start_time, reversed=True) else: time_left = 'overdue!' participants = [] for participant in approval.event.participants.all(): participants.append(participant.name) participants = ' and '.join(participants) text = render_to_string( 'manage/_pester_approval_event.html', { 'approval': approval, 'event': approval.event, 'time_left': time_left, 'manage_url': build_absolute_url( reverse('manage:approval_review', args=(approval.pk, )), ), }) approval_texts[approval] = text texts.append(approval_texts[approval]) cache_keys.append('pestered-%s-%s' % (user.pk, approval.pk)) group_names = [x.name for x in user.groups.all()] message = render_to_string( 'manage/_pester_approvals.html', { 'texts': texts, 'group_names': ' and '.join(group_names), 'approvals_url': build_absolute_url( reverse('manage:approvals')) }) subject = '[Air Mozilla] Approval reminder. You have ' if len(texts) == 1: subject += '1 event ' else: subject += '%s events ' % len(texts) subject += 'to approve.' email = EmailMessage(subject, message, settings.EMAIL_FROM_ADDRESS, [user.email]) emails_sent.append((user.email, subject, message)) if not dry_run: email.send() for cache_key in cache_keys: cache.set(cache_key, True, INTERVAL) return emails_sent
def status_last_updated(self, app): if not app.status_update_date: return None return timesince(app.status_update_date)
def age(self): return timesince(self.timestamp)
def test_display_second_before_first(self): """ When the second date occurs before the first, we should always get 0 minutes. """ self.assertEqual(timesince(self.t, self.t - self.onemicrosecond), '0\xa0minutes') self.assertEqual(timesince(self.t, self.t - self.onesecond), '0\xa0minutes') self.assertEqual(timesince(self.t, self.t - self.oneminute), '0\xa0minutes') self.assertEqual(timesince(self.t, self.t - self.onehour), '0\xa0minutes') self.assertEqual(timesince(self.t, self.t - self.oneday), '0\xa0minutes') self.assertEqual(timesince(self.t, self.t - self.oneweek), '0\xa0minutes') self.assertEqual(timesince(self.t, self.t - self.onemonth), '0\xa0minutes') self.assertEqual(timesince(self.t, self.t - self.oneyear), '0\xa0minutes') self.assertEqual( timesince(self.t, self.t - 2 * self.oneday - 6 * self.onehour), '0\xa0minutes') self.assertEqual( timesince(self.t, self.t - 2 * self.oneweek - 2 * self.oneday), '0\xa0minutes') self.assertEqual( timesince( self.t, self.t - 2 * self.oneweek - 3 * self.onehour - 4 * self.oneminute), '0\xa0minutes') self.assertEqual( timesince(self.t, self.t - 4 * self.oneday - 5 * self.oneminute), '0\xa0minutes')
def timesince(value, *arg): if value is None or isinstance(value, Undefined): return u'' from django.utils.timesince import timesince return timesince(value, *arg)
def modified(self, obj): if not obj.action_time: return "Never" return "{} ago".format(timesince(obj.action_time))
def get_updated_at(self, instance): return timesince(instance.updated_at)
def test_equal_datetimes(self): """ equal datetimes. """ # NOTE: \xa0 avoids wrapping between value and unit self.assertEqual(timesince(self.t, self.t), '0\xa0minutes')
def test_ignore_microseconds_and_seconds(self): """ Microseconds and seconds are ignored. """ self.assertEqual(timesince(self.t, self.t + self.onemicrosecond), '0\xa0minutes') self.assertEqual(timesince(self.t, self.t + self.onesecond), '0\xa0minutes')
def get_created_at(self, instance): return timesince(instance.created_at)
def get_time_since(self, obj): instance = obj.first_message() if instance: return timesince(instance.sent_at) return ''
def render_last_ping(self, record): return timesince(record.last_ping)
def short_timesince(value): return timesince(value).split(',')[0]
def get_timesince(self, instance): return timesince(instance.date_modified) + "ago"
def age(self): # simple example #return timesince(self.cdt) # for getting since time from created date return "{}ago".format(timesince(self.cdt) ) # modified with .format
def nav_subtitle(self): if self.enabled and self.last_invalidation is not None: return (_('Last invalidation: %s') % timesince(self.last_invalidation)) return ''
def get_timesince(self, obj): return timesince(obj.created) + " ago"
def test_leap_year(self): start_date = datetime.date(2016, 12, 25) self.assertEqual(timeuntil(start_date + self.oneweek, start_date), '1\xa0week') self.assertEqual(timesince(start_date, start_date + self.oneweek), '1\xa0week')
def joined(self, obj): return timesince(obj.date_joined) + ' ago'
def test_thousand_years_ago(self): t = datetime.datetime(1007, 8, 14, 13, 46, 0) self.assertEqual(timesince(t, self.t), '1000\xa0years') self.assertEqual(timeuntil(self.t, t), '1000\xa0years')