Python django.utils.timezone.localtime() Examples

The following are 30 code examples for showing how to use django.utils.timezone.localtime(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .

Example 1
Project: django-healthchecks   Author: mvantellingen   File: admin.py    License: MIT License 6 votes vote down vote up
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
Project: StormOnline   Author: stormsha   File: util.py    License: Apache License 2.0 6 votes vote down vote up
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.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example 3
Project: GTDWeb   Author: lanbing510   File: tz.py    License: GNU General Public License v2.0 6 votes vote down vote up
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
Project: linkedevents   Author: City-of-Helsinki   File: test_event_post.py    License: MIT License 6 votes vote down vote up
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 5
Project: linkedevents   Author: City-of-Helsinki   File: test_event_put.py    License: MIT License 6 votes vote down vote up
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 6
Project: bioforum   Author: reBiocoder   File: tz.py    License: MIT License 6 votes vote down vote up
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 7
Project: karrot-backend   Author: yunity   File: tasks.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 8
Project: karrot-backend   Author: yunity   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 9
Project: civet   Author: idaholab   File: views.py    License: Apache License 2.0 6 votes vote down vote up
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 10
Project: hawkpost   Author: whitesmith   File: forms.py    License: MIT License 6 votes vote down vote up
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 11
Project: weibo-analysis-system   Author: Superbsco   File: util.py    License: MIT License 6 votes vote down vote up
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 12
Project: django-modelcluster   Author: wagtail   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 13
Project: myblog   Author: myminwang   File: util.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 14
Project: CTF_AWD_Platform   Author: xuchaoa   File: util.py    License: MIT License 6 votes vote down vote up
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 15
Project: django_OA   Author: abaoMAO   File: util.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 16
Project: zing   Author: evernote   File: invoice.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 17
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: tz.py    License: MIT License 6 votes vote down vote up
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 18
Project: healthchecks   Author: healthchecks   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 19
Project: python   Author: Yeah-Kun   File: tz.py    License: Apache License 2.0 6 votes vote down vote up
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 20
Project: luscan-devel   Author: blackye   File: tz.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 21
Project: StormOnline   Author: stormsha   File: util.py    License: Apache License 2.0 5 votes vote down vote up
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
Project: jbox   Author: jpush   File: fields.py    License: MIT License 5 votes vote down vote up
def _value(self):
        date = self.data

        if settings.USE_TZ and isinstance(date, datetime.datetime) and timezone.is_aware(date):
            self.data = timezone.localtime(date)

        return super(DateTimeField, self)._value() 
Example 23
Project: resolwe   Author: genialis   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def _get_mtime(self, entry: datetime):
        """Convert datetime entry to nginx autoindex compatible string.

        The timezone returned by autoindex module was set to GMT so we convert
        from our timetone to GMT.
        """
        gmt = timezone.localtime(entry, pytz.timezone("GMT"))
        return gmt.strftime("%a, %d %b %Y %H:%M:%S %Z") 
Example 24
Project: django-angularjs-blog   Author: bluedazzle   File: utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def datetime_to_utc_string(datetimet):
    return str(timezone.localtime(datetimet)) 
Example 25
Project: GTDWeb   Author: lanbing510   File: dates.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 26
Project: GTDWeb   Author: lanbing510   File: tz.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 27
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _sqlite_datetime_extract(lookup_type, 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))
    if lookup_type == 'week_day':
        return (dt.isoweekday() % 7) + 1
    else:
        return getattr(dt, lookup_type) 
Example 28
Project: django-csp-reports   Author: adamalton   File: utils.py    License: MIT License 5 votes vote down vote up
def get_midnight():
    """Return last midnight in localtime as datetime.

    @return: Midnight datetime
    """
    limit = now()
    if settings.USE_TZ:
        limit = localtime(limit)
    return limit.replace(hour=0, minute=0, second=0, microsecond=0) 
Example 29
Project: linkedevents   Author: City-of-Helsinki   File: docx.py    License: MIT License 5 votes vote down vote up
def parse_event(self, raw_event):
        '''
        Turns a raw event into a dictionary with only needed fields.
        Keeps track of earliest and latest times encountered.
        '''
        start_time = localtime(raw_event['start_time_obj'])
        end_time = localtime(raw_event['end_time_obj'])

        if self.earliest_date is None or start_time.date() < self.earliest_date:
            self.earliest_date = start_time.date()

        if self.latest_date is None or end_time.date() > self.latest_date:
            self.latest_date = start_time.date()

        price = get_price(raw_event)
        if price is not None:
            price = get_any_language(price)
        else:
            price = ''

        return {
            'name': get_any_language(raw_event['name']),
            'description': strip_tags(
                get_any_language(get_description(raw_event))
            ),
            'location': raw_event['location'],
            'start_time': start_time,
            'end_time': end_time,
            'price': price,
        } 
Example 30
Project: bioforum   Author: reBiocoder   File: tz.py    License: MIT License 5 votes vote down vote up
def localtime(value):
    """
    Convert 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())