Python django.utils.timezone.localtime() Examples
The following are 30
code examples of django.utils.timezone.localtime().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.utils.timezone
, or try the search function
.
Example #1
Source File: admin.py From django-healthchecks with MIT License | 7 votes |
def last_beat_column(self, object): last_beat = object.last_beat if is_aware(last_beat): # Only for USE_TZ=True last_beat = localtime(last_beat) last_beat_str = localize(last_beat) if object.is_expired: # Make clearly visible alert_icon = static('admin/img/icon-alert.svg') return format_html( '<div style="vertical-align: middle; display: inline-block;">' ' <img src="{}" style="vertical-align: middle;"> ' ' <span style="color: #efb80b; vertical-align: middle;">{}</span>' '</div>', alert_icon, last_beat_str ) else: return last_beat_str
Example #2
Source File: models.py From django-modelcluster with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_field_value(field, model): if field.remote_field is None: value = field.pre_save(model, add=model.pk is None) # Make datetimes timezone aware # https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L1394-L1403 if isinstance(value, datetime.datetime) and settings.USE_TZ: if timezone.is_naive(value): default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone).astimezone(timezone.utc) # convert to UTC value = timezone.localtime(value, timezone.utc) if is_protected_type(value): return value else: return field.value_to_string(model) else: return getattr(model, field.get_attname())
Example #3
Source File: tz.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def localtime_tag(parser, token): """ Forces or prevents conversion of datetime objects to local time, regardless of the value of ``settings.USE_TZ``. Sample usage:: {% localtime off %}{{ value_in_utc }}{% endlocaltime %} """ bits = token.split_contents() if len(bits) == 1: use_tz = True elif len(bits) > 2 or bits[1] not in ('on', 'off'): raise TemplateSyntaxError("%r argument should be 'on' or 'off'" % bits[0]) else: use_tz = bits[1] == 'on' nodelist = parser.parse(('endlocaltime',)) parser.delete_first_token() return LocalTimeNode(nodelist, use_tz)
Example #4
Source File: tz.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def localtime_tag(parser, token): """ Forces or prevents conversion of datetime objects to local time, regardless of the value of ``settings.USE_TZ``. Sample usage:: {% localtime off %}{{ value_in_utc }}{% endlocaltime %} """ bits = token.split_contents() if len(bits) == 1: use_tz = True elif len(bits) > 2 or bits[1] not in ('on', 'off'): raise TemplateSyntaxError("%r argument should be 'on' or 'off'" % bits[0]) else: use_tz = bits[1] == 'on' nodelist = parser.parse(('endlocaltime',)) parser.delete_first_token() return LocalTimeNode(nodelist, use_tz)
Example #5
Source File: tz.py From python with Apache License 2.0 | 6 votes |
def localtime_tag(parser, token): """ Forces or prevents conversion of datetime objects to local time, regardless of the value of ``settings.USE_TZ``. Sample usage:: {% localtime off %}{{ value_in_utc }}{% endlocaltime %} """ bits = token.split_contents() if len(bits) == 1: use_tz = True elif len(bits) > 2 or bits[1] not in ('on', 'off'): raise TemplateSyntaxError("%r argument should be 'on' or 'off'" % bits[0]) else: use_tz = bits[1] == 'on' nodelist = parser.parse(('endlocaltime',)) parser.delete_first_token() return LocalTimeNode(nodelist, use_tz)
Example #6
Source File: test_event_post.py From linkedevents with MIT License | 6 votes |
def test__autopopulated_fields_at_create( api_client, minimal_event_dict, user, user2, other_data_source, organization, organization2): # create an event api_client.force_authenticate(user=user) response = create_with_post(api_client, minimal_event_dict) event = Event.objects.get(id=response.data['id']) assert event.created_by == user assert event.last_modified_by == user assert event.created_time is not None assert event.last_modified_time is not None assert event.data_source.id == settings.SYSTEM_DATA_SOURCE_ID assert event.publisher == organization # events are automatically marked as ending at midnight, local time assert event.end_time == timezone.localtime(timezone.now() + timedelta(days=2)).\ replace(hour=0, minute=0, second=0, microsecond=0).astimezone(pytz.utc) assert event.has_end_time is False # the following values may not be posted
Example #7
Source File: test_event_put.py From linkedevents with MIT License | 6 votes |
def test__update_minimal_event_with_autopopulated_fields_with_put(api_client, minimal_event_dict, user, organization): # create an event api_client.force_authenticate(user=user) response = create_with_post(api_client, minimal_event_dict) data = response.data assert_event_data_is_equal(minimal_event_dict, data) event_id = data['@id'] response2 = update_with_put(api_client, event_id, minimal_event_dict) assert_event_data_is_equal(data, response2.data) event = Event.objects.get(id=data['id']) assert event.created_by == user assert event.last_modified_by == user assert event.created_time is not None assert event.last_modified_time is not None assert event.data_source.id == settings.SYSTEM_DATA_SOURCE_ID assert event.publisher == organization # events are automatically marked as ending at midnight, local time assert event.end_time == timezone.localtime(timezone.now() + timedelta(days=2)).\ replace(hour=0, minute=0, second=0, microsecond=0).astimezone(pytz.utc) assert event.has_end_time is False
Example #8
Source File: views.py From healthchecks with BSD 3-Clause "New" or "Revised" License | 6 votes |
def cron_preview(request): schedule = request.POST.get("schedule", "") tz = request.POST.get("tz") ctx = {"tz": tz, "dates": []} try: zone = pytz.timezone(tz) now_local = timezone.localtime(timezone.now(), zone) if len(schedule.split()) != 5: raise ValueError() it = croniter(schedule, now_local) for i in range(0, 6): ctx["dates"].append(it.get_next(datetime)) ctx["desc"] = str(ExpressionDescriptor(schedule, use_24hour_time_format=True)) except UnknownTimeZoneError: ctx["bad_tz"] = True except: ctx["bad_schedule"] = True return render(request, "front/cron_preview.html", ctx)
Example #9
Source File: tasks.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
def daily_activity_notifications(): with timer() as t: for group in Group.objects.all(): with timezone.override(group.timezone): if timezone.localtime().hour != 20: # only at 8pm local time continue for data in fetch_activity_notification_data_for_group(group): prepare_activity_notification_email(**data).send() stats.activity_notification_email( group=data['group'], **{k: v.count() for k, v in data.items() if isinstance(v, QuerySet)} ) stats_utils.periodic_task('activities__daily_activity_notifications', seconds=t.elapsed_seconds)
Example #10
Source File: invoice.py From zing with GNU General Public License v3.0 | 6 votes |
def _check_single_paidtask(invoice, amount): server_tz = timezone.get_default_timezone() local_now = timezone.localtime(invoice.now, server_tz) current_month_start = local_now.replace( day=1, hour=0, minute=0, second=0, microsecond=0 ) PaidTask.objects.get( task_type=PaidTaskTypes.CORRECTION, amount=(-1) * amount, datetime=invoice.month_end, description="Carryover to the next month", user=invoice.user, ) PaidTask.objects.get( task_type=PaidTaskTypes.CORRECTION, amount=amount, datetime=current_month_start, description="Carryover from the previous month", user=invoice.user, )
Example #11
Source File: views.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
def activity_notification(self): user = random_user() activity1 = Activity.objects.order_by('?').first() activity2 = Activity.objects.order_by('?').first() activity3 = Activity.objects.order_by('?').first() activity4 = Activity.objects.order_by('?').first() localtime = timezone.localtime() return prepare_activity_notification_email( user=user, group=user.groups.first(), tonight_date=localtime, tomorrow_date=localtime + relativedelta(days=1), tonight_user=[activity1, activity2], tonight_empty=[activity3, activity4], tonight_not_full=[activity4], tomorrow_user=[activity2], tomorrow_empty=[activity3], tomorrow_not_full=[activity4], )
Example #12
Source File: tz.py From bioforum with MIT License | 6 votes |
def localtime_tag(parser, token): """ Force or prevent conversion of datetime objects to local time, regardless of the value of ``settings.USE_TZ``. Sample usage:: {% localtime off %}{{ value_in_utc }}{% endlocaltime %} """ bits = token.split_contents() if len(bits) == 1: use_tz = True elif len(bits) > 2 or bits[1] not in ('on', 'off'): raise TemplateSyntaxError("%r argument should be 'on' or 'off'" % bits[0]) else: use_tz = bits[1] == 'on' nodelist = parser.parse(('endlocaltime',)) parser.delete_first_token() return LocalTimeNode(nodelist, use_tz)
Example #13
Source File: views.py From civet with Apache License 2.0 | 6 votes |
def main_update(request): """ Get the updates for the main page. """ if 'last_request' not in request.GET or 'limit' not in request.GET: return HttpResponseBadRequest('Missing parameters') this_request = TimeUtils.get_local_timestamp() limit = int(request.GET['limit']) last_request = int(float(request.GET['last_request'])) # in case it has decimals dt = timezone.localtime(timezone.make_aware(datetime.datetime.utcfromtimestamp(last_request))) repos_data, einfo, default = views.get_user_repos_info(request, limit=limit, last_modified=dt) # we also need to check if a PR closed recently closed = [] for pr in models.PullRequest.objects.filter(closed=True, last_modified__gte=dt).values('id').all(): closed.append({'id': pr['id']}) return JsonResponse({'repo_status': repos_data, 'closed': closed, 'last_request': this_request, 'events': einfo, 'limit': limit, })
Example #14
Source File: forms.py From hawkpost with MIT License | 6 votes |
def clean_expires_at(self): # Validate the expiration date expires_at = self.cleaned_data.get("expires_at", "") never_expires = self.cleaned_data.get("never_expires", "") current_tz = timezone.get_current_timezone() if never_expires: expires_at = None self.cleaned_data["expires_at"] = expires_at if expires_at: # Check if the expiration date is a past date if timezone.localtime(timezone.now(), current_tz) > expires_at: self.add_error('expires_at', _('The date must be on the future.')) if not expires_at and not never_expires: self.add_error('expires_at', _('This field is required, unless box is set to ' 'never expire.')) return expires_at
Example #15
Source File: tz.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def localtime_tag(parser, token): """ Force or prevent conversion of datetime objects to local time, regardless of the value of ``settings.USE_TZ``. Sample usage:: {% localtime off %}{{ value_in_utc }}{% endlocaltime %} """ bits = token.split_contents() if len(bits) == 1: use_tz = True elif len(bits) > 2 or bits[1] not in ('on', 'off'): raise TemplateSyntaxError("%r argument should be 'on' or 'off'" % bits[0]) else: use_tz = bits[1] == 'on' nodelist = parser.parse(('endlocaltime',)) parser.delete_first_token() return LocalTimeNode(nodelist, use_tz)
Example #16
Source File: base.py From python with Apache License 2.0 | 5 votes |
def _sqlite_datetime_parse(dt, tzname): if dt is None: return None try: dt = backend_utils.typecast_timestamp(dt) except (ValueError, TypeError): return None if tzname is not None: dt = timezone.localtime(dt, pytz.timezone(tzname)) return dt
Example #17
Source File: timestamps.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def submittable_timestamp(timestamp): """ Helper function to translate a possibly-timezone-aware datetime into the format used in the go_live_at / expire_at form fields - "YYYY-MM-DD hh:mm", with no timezone indicator. This will be interpreted as being in the server's timezone (settings.TIME_ZONE), so we need to pass it through timezone.localtime to ensure that the client and server are in agreement about what the timestamp means. """ return timezone.localtime(timestamp).strftime("%Y-%m-%d %H:%M")
Example #18
Source File: date.py From graphene-django-extras with MIT License | 5 votes |
def _format_time_ago(dt, now=None, full=False, ago_in=False, two_days=False): if not isinstance(dt, timedelta): if now is None: now = timezone.localtime( timezone=timezone.get_fixed_timezone(-int(t.timezone / 60)) ) original_dt = dt dt = _parse(dt) now = _parse(now) if dt is None: raise ValueError( "The parameter `dt` should be datetime timedelta, or datetime formatted string." ) if now is None: raise ValueError( "the parameter `now` should be datetime, or datetime formatted string." ) result = relativedelta.relativedelta(dt, now) flag, result = _format_relativedelta(result, full, two_days, original_dt) if ago_in and flag is not None: result = "in {}".format(result) if flag else "{} ago".format(result) return result
Example #19
Source File: dates.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def timezone_today(): """ Return the current date in the current time zone. """ if settings.USE_TZ: return timezone.localtime(timezone.now()).date() else: return datetime.date.today()
Example #20
Source File: tz.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def localtime(value): """ Converts a datetime to local time in the active time zone. This only makes sense within a {% localtime off %} block. """ return do_timezone(value, timezone.get_current_timezone())
Example #21
Source File: util.py From django_OA with GNU General Public License v3.0 | 5 votes |
def display_for_value(value, boolean=False): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if boolean: return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(value, datetime.datetime): return formats.localize(tz_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, (decimal.Decimal, float)): return formats.number_format(value) else: return smart_text(value)
Example #22
Source File: util.py From django_OA with GNU General Public License v3.0 | 5 votes |
def display_for_field(value, field): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.remote_field, models.ManyToManyRel): return ', '.join([smart_text(obj) for obj in value.all()]) else: return smart_text(value)
Example #23
Source File: util.py From CTF_AWD_Platform with MIT License | 5 votes |
def display_for_value(value, boolean=False): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if boolean: return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(value, datetime.datetime): return formats.localize(tz_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, (decimal.Decimal, float)): return formats.number_format(value) else: return smart_text(value)
Example #24
Source File: util.py From CTF_AWD_Platform with MIT License | 5 votes |
def display_for_field(value, field): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.remote_field, models.ManyToManyRel): return ', '.join([smart_text(obj) for obj in value.all()]) else: return smart_text(value)
Example #25
Source File: util.py From myblog with GNU Affero General Public License v3.0 | 5 votes |
def display_for_value(value, boolean=False): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if boolean: return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(value, datetime.datetime): return formats.localize(tz_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, (decimal.Decimal, float)): return formats.number_format(value) else: return smart_text(value)
Example #26
Source File: util.py From myblog with GNU Affero General Public License v3.0 | 5 votes |
def display_for_field(value, field): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.remote_field, models.ManyToManyRel): return ', '.join([smart_text(obj) for obj in value.all()]) else: return smart_text(value)
Example #27
Source File: contests.py From online-judge with GNU Affero General Public License v3.0 | 5 votes |
def get_contest_data(self, start, end): end += timedelta(days=1) contests = self.get_queryset().filter(Q(start_time__gte=start, start_time__lt=end) | Q(end_time__gte=start, end_time__lt=end)) starts, ends, oneday = (defaultdict(list) for i in range(3)) for contest in contests: start_date = timezone.localtime(contest.start_time).date() end_date = timezone.localtime(contest.end_time - timedelta(seconds=1)).date() if start_date == end_date: oneday[start_date].append(contest) else: starts[start_date].append(contest) ends[end_date].append(contest) return starts, ends, oneday
Example #28
Source File: views.py From celery-monitor with GNU General Public License v3.0 | 5 votes |
def get(self,request): task_name = self.request.GET.get('task_name',None) start_time = self.request.GET.get('start_time',(datetime.datetime.now() - datetime.timedelta(days=3)).strftime('%Y-%m-%d %H:%M:%S')) end_time = self.request.GET.get('end_time',datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) def tstamp(object): return time.mktime(localtime(object.tstamp).timetuple()) * 1000 data = [[tstamp(i),i.runtime] for i in TaskState.objects.filter(tstamp__range=[start_time,end_time]).filter(name=task_name).exclude(result__contains='running').order_by('tstamp') ] chart_data = {'name':task_name,'data':data} return HttpResponse(json.dumps(chart_data),content_type="application/json")
Example #29
Source File: dates.py From openhgsenti with Apache License 2.0 | 5 votes |
def timezone_today(): """ Return the current date in the current time zone. """ if settings.USE_TZ: return timezone.localtime(timezone.now()).date() else: return datetime.date.today()
Example #30
Source File: invoice.py From zing with GNU General Public License v3.0 | 5 votes |
def _add_carry_over(self, total_amount): """Adds a carry-over correction for the value of `total_amount` from the month being processed to the next month. """ server_tz = timezone.get_default_timezone() local_now = timezone.localtime(self.now, server_tz) initial_moment = local_now.replace( day=1, hour=0, minute=0, second=0, microsecond=0 ) PaidTask.objects.get_or_create( task_type=PaidTaskTypes.CORRECTION, amount=(-1) * total_amount, rate=1, datetime=self.month_end, description="Carryover to the next month", user=self.user, ) PaidTask.objects.get_or_create( task_type=PaidTaskTypes.CORRECTION, amount=total_amount, rate=1, datetime=initial_moment, description="Carryover from the previous month", user=self.user, )