Python django.utils.timezone.get_current_timezone() Examples

The following are 30 code examples for showing how to use django.utils.timezone.get_current_timezone(). 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: resolwe   Author: genialis   File: test_filtering.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.viewset_class = DescriptorSchemaViewSet
        super().setUp()

        tzone = get_current_timezone()

        self.ds1 = DescriptorSchema.objects.create(
            contributor=self.user, slug="slug1", name="ds1"
        )
        self.ds1.created = datetime.datetime(2015, 7, 28, 11, 57, tzinfo=tzone)
        self.ds1.save()

        self.ds2 = DescriptorSchema.objects.create(
            contributor=self.user, slug="slug2", name="ds2"
        )
        self.ds2.created = datetime.datetime(2016, 8, 29, 12, 58, 0, tzinfo=tzone)
        self.ds2.save()

        self.ds3 = DescriptorSchema.objects.create(
            contributor=self.admin, slug="slug3", name="ds3"
        )
        self.ds3.created = datetime.datetime(2017, 9, 30, 13, 59, 0, tzinfo=tzone)
        self.ds3.save() 
Example 2
Project: resolwe   Author: genialis   File: test_viewsets.py    License: Apache License 2.0 6 votes vote down vote up
def test_lookup_expressions_exact(self):
        from .test_app.models import TestModel

        tzone = get_current_timezone()
        TestModel.objects.create(
            name="Object name 4",
            number=45,
            date=datetime.datetime(2016, 1, 1, 0, 0, tzinfo=tzone),
            field_process_type="foo:bar:moo:",
        )

        response = self._make_request(field_process_type="foo:bar")
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["name"], "Object name 4")

        response = self._make_request(field_process_type__exact="foo:bar")
        self.assertEqual(len(response.data), 0)

        response = self._make_request(field_process_type__exact="foo:bar:moo:")
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["name"], "Object name 4") 
Example 3
Project: GTDWeb   Author: lanbing510   File: utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value 
Example 4
Project: GTDWeb   Author: lanbing510   File: tz.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_current_timezone_tag(parser, token):
    """
    Stores the name of the current time zone in the context.

    Usage::

        {% get_current_timezone as TIME_ZONE %}

    This will fetch the currently active time zone and put its name
    into the ``TIME_ZONE`` context variable.
    """
    # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
    args = token.contents.split()
    if len(args) != 3 or args[1] != 'as':
        raise TemplateSyntaxError("'get_current_timezone' requires "
                                  "'as variable' (got %r)" % args)
    return GetCurrentTimezoneNode(args[2]) 
Example 5
Project: GTDWeb   Author: lanbing510   File: query.py    License: GNU General Public License v2.0 6 votes vote down vote up
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
        """
        Returns a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        """
        assert kind in ("year", "month", "day", "hour", "minute", "second"), \
            "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'."
        assert order in ('ASC', 'DESC'), \
            "'order' must be either 'ASC' or 'DESC'."
        if settings.USE_TZ:
            if tzinfo is None:
                tzinfo = timezone.get_current_timezone()
        else:
            tzinfo = None
        return self.annotate(
            datetimefield=DateTime(field_name, kind, tzinfo),
            plain_field=F(field_name)
        ).values_list(
            'datetimefield', flat=True
        ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield') 
Example 6
Project: woid   Author: vitorfs   File: crawlers.py    License: Apache License 2.0 6 votes vote down vote up
def update_top_stories(self):
        try:
            posts = self.client.get_top_posts()
            today = timezone.now()
            for post in posts:
                code = post['slug']
                story, created = Story.objects.get_or_create(
                    service=self.service,
                    code=code,
                    date=timezone.datetime(today.year, today.month, today.day, tzinfo=timezone.get_current_timezone())
                )

                if created:
                    story.title = post['name']
                    story.description = post['tagline']
                    story.url = u'{0}{1}'.format(self.service.story_url, code)

                story.score = post['votes_count']
                story.comments = post['comments_count']
                story.status = Story.OK
                story.save()

        except Exception:
            logger.exception('An error occurred while executing `update_top_stores` for Product Hunt.')
            raise 
Example 7
Project: bioforum   Author: reBiocoder   File: utils.py    License: MIT License 6 votes vote down vote up
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception as exc:
            raise ValidationError(
                _('%(datetime)s couldn\'t be interpreted '
                  'in time zone %(current_timezone)s; it '
                  'may be ambiguous or it may not exist.'),
                code='ambiguous_timezone',
                params={'datetime': value, 'current_timezone': current_timezone}
            ) from exc
    return value 
Example 8
Project: bioforum   Author: reBiocoder   File: tz.py    License: MIT License 6 votes vote down vote up
def get_current_timezone_tag(parser, token):
    """
    Store the name of the current time zone in the context.

    Usage::

        {% get_current_timezone as TIME_ZONE %}

    This will fetch the currently active time zone and put its name
    into the ``TIME_ZONE`` context variable.
    """
    # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
    args = token.contents.split()
    if len(args) != 3 or args[1] != 'as':
        raise TemplateSyntaxError("'get_current_timezone' requires "
                                  "'as variable' (got %r)" % args)
    return GetCurrentTimezoneNode(args[2]) 
Example 9
Project: bioforum   Author: reBiocoder   File: query.py    License: MIT License 6 votes vote down vote up
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
        """
        Return a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        """
        assert kind in ("year", "month", "day", "hour", "minute", "second"), \
            "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'."
        assert order in ('ASC', 'DESC'), \
            "'order' must be either 'ASC' or 'DESC'."
        if settings.USE_TZ:
            if tzinfo is None:
                tzinfo = timezone.get_current_timezone()
        else:
            tzinfo = None
        return self.annotate(
            datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo),
            plain_field=F(field_name)
        ).values_list(
            'datetimefield', flat=True
        ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield') 
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: janeway   Author: BirkbeckCTP   File: shared.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def parse_date(date_string, is_iso):
    """ Parse a date from a string according to timezone-specific settings

    :param date_string: the date string to be parsed
    :param is_iso: whether or not to use ISO-specific formatting settings ("%Y-%m-%dT%H:%M:%S" if True, otherwise
    "%Y-%m-%d"
    :return: a timezone object of the parsed date
    """
    if date_string is not None and date_string != "":
        if is_iso:
            return timezone.make_aware(datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S"),
                                       timezone.get_current_timezone())
        else:
            return timezone.make_aware(datetime.strptime(date_string, "%Y-%m-%d"), timezone.get_current_timezone())
    else:
        print("Returning current datetime as no valid datetime was given")
        return timezone.now() 
Example 12
Project: openduty   Author: ustream   File: escalation_helper.py    License: MIT License 6 votes vote down vote up
def get_events_users_inbetween(calendar, since, until):
    delta = until - since
    result = {}
    for i in range(delta.days + 1):
        that_day = since + timedelta(days=i)
        that_day = timezone.make_aware(that_day, timezone.get_current_timezone())
        day = Day(calendar.events.all(), that_day)
        for o in day.get_occurrences():
            if o.start <= that_day <= o.end:
                usernames = o.event.title.split(',')
                for username in usernames:
                    if username not in result.keys():
                        user_instance = User.objects.get(username=username.strip())
                        result[username] = {"start": o.start, "person": username.strip(), "end": o.end,
                                            "email": user_instance.email}
                    else:
                        result[username]["end"] = o.end
    return result.values() 
Example 13
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: utils.py    License: MIT License 6 votes vote down vote up
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception as exc:
            raise ValidationError(
                _('%(datetime)s couldn\'t be interpreted '
                  'in time zone %(current_timezone)s; it '
                  'may be ambiguous or it may not exist.'),
                code='ambiguous_timezone',
                params={'datetime': value, 'current_timezone': current_timezone}
            ) from exc
    return value 
Example 14
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: tz.py    License: MIT License 6 votes vote down vote up
def get_current_timezone_tag(parser, token):
    """
    Store the name of the current time zone in the context.

    Usage::

        {% get_current_timezone as TIME_ZONE %}

    This will fetch the currently active time zone and put its name
    into the ``TIME_ZONE`` context variable.
    """
    # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
    args = token.contents.split()
    if len(args) != 3 or args[1] != 'as':
        raise TemplateSyntaxError("'get_current_timezone' requires "
                                  "'as variable' (got %r)" % args)
    return GetCurrentTimezoneNode(args[2]) 
Example 15
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: operations.py    License: MIT License 6 votes vote down vote up
def year_lookup_bounds_for_datetime_field(self, value):
        """
        Return a two-elements list with the lower and upper bound to be used
        with a BETWEEN operator to query a DateTimeField value using a year
        lookup.

        `value` is an int, containing the looked-up year.
        """
        first = datetime.datetime(value, 1, 1)
        second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999)
        if settings.USE_TZ:
            tz = timezone.get_current_timezone()
            first = timezone.make_aware(first, tz)
            second = timezone.make_aware(second, tz)
        first = self.adapt_datetimefield_value(first)
        second = self.adapt_datetimefield_value(second)
        return [first, second] 
Example 16
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: query.py    License: MIT License 6 votes vote down vote up
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
        """
        Return a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        """
        assert kind in ('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), \
            "'kind' must be one of 'year', 'month', 'week', 'day', 'hour', 'minute', or 'second'."
        assert order in ('ASC', 'DESC'), \
            "'order' must be either 'ASC' or 'DESC'."
        if settings.USE_TZ:
            if tzinfo is None:
                tzinfo = timezone.get_current_timezone()
        else:
            tzinfo = None
        return self.annotate(
            datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo),
            plain_field=F(field_name)
        ).values_list(
            'datetimefield', flat=True
        ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield') 
Example 17
Project: bennedetto   Author: arecker   File: tests.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_date_filter(self):
        mock = Transaction()
        mock.amount = Decimal(10)
        mock.description = 'Date Test'
        mock.user = User.objects.create_user('hello@test.com')
        mock.user.activate_timezone()
        mock.timestamp = datetime.datetime(2014, 1, 1, 8, 15, 2, 0, timezone.get_current_timezone())
        mock.save()

        filter_date = datetime.datetime.combine(datetime.datetime(2014, 1, 1),
                                                datetime.time.max)
        actual = Transaction.objects.date(filter_date).first()
        self.assertEqual(actual.description, 'Date Test')

        filter_date = datetime.datetime(2014, 1, 2, 8, 15, 2, 0, timezone.get_current_timezone())
        actual = Transaction.objects.date(filter_date).exists()
        self.assertFalse(actual) 
Example 18
Project: bennedetto   Author: arecker   File: tests.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_date_range_filter(self):
        mock = Transaction()
        mock.amount = Decimal(10)
        mock.description = 'Date Range Test'
        mock.user = User.objects.create_user('hello@test.com')
        mock.user.activate_timezone()
        mock.timestamp = datetime.datetime(2014, 1, 1, 8, 15, 2, 0, timezone.get_current_timezone())
        mock.save()

        start = datetime.datetime(2013, 12, 31, 5, 5, 5, 5,  timezone.get_current_timezone())
        end = datetime.datetime(2014, 1, 1, 0, 0, 0, 0, timezone.get_current_timezone())
        actual = Transaction.objects.date_range(start, end).first()
        self.assertEqual(actual.description, 'Date Range Test')

        end = datetime.datetime(2013, 12, 31, 12, 12, 12, 12, timezone.get_current_timezone())
        actual = Transaction.objects.date_range(start, end).exists()
        self.assertFalse(actual) 
Example 19
Project: django-leonardo   Author: django-leonardo   File: imagemodels.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def save(self, *args, **kwargs):
        if self.date_taken is None:
            try:
                exif_date = self.exif.get('DateTimeOriginal', None)
                if exif_date is not None:
                    d, t = exif_date.split(" ")
                    year, month, day = d.split(':')
                    hour, minute, second = t.split(':')
                    if getattr(settings, "USE_TZ", False):
                        tz = get_current_timezone()
                        self.date_taken = make_aware(datetime(
                            int(year), int(month), int(day),
                            int(hour), int(minute), int(second)), tz)
                    else:
                        self.date_taken = datetime(
                            int(year), int(month), int(day),
                            int(hour), int(minute), int(second))
            except Exception:
                pass
        if self.date_taken is None:
            self.date_taken = now()
        super(Image, self).save(*args, **kwargs) 
Example 20
Project: srvup-rest-framework   Author: codingforentrepreneurs   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def update_braintree_membership(user):
	user = user
	membership = user.membership
	now = timezone.now()
	subscription_id = user.usermerchantid.subscription_id
	if membership.date_end <= timezone.now() and subscription_id is not None:
		status, next_billing_date = check_membership_status(subscription_id)
		if status:
			small_time = datetime.time(0,0,0,1)
			datetime_obj = datetime.datetime.combine(next_billing_date, small_time)
			datetime_aware = timezone.make_aware(datetime_obj, timezone.get_current_timezone())
			membership_dates_update.send(membership, new_date_start=datetime_aware)
		else:
			membership.update_status()
	elif subscription_id is None:
		membership.update_status()
	else:
		pass 
Example 21
Project: Servo   Author: fpsw   File: account.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clear_notifications(request):
    from datetime import datetime
    ts = [int(x) for x in request.GET.get('t').split('/')]
    ts = datetime(*ts, tzinfo=timezone.get_current_timezone())
    notif = request.user.notifications.filter(handled_at=None)
    notif.filter(triggered_at__lt=ts).update(handled_at=timezone.now())
    messages.success(request, _('All notifications cleared'))
    return redirect(request.META['HTTP_REFERER']) 
Example 22
Project: Servo   Author: fpsw   File: checkescalations.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handle(self, *args, **options):
        # get local user to create notes as
        uid = Configuration.conf('imap_act')
        
        if empty(uid):
            raise ConfigurationError('Incoming message user not defined')

        user = User.objects.get(pk=uid)
        tz = timezone.get_current_timezone()
        
        for i in Escalation.objects.exclude(Q(escalation_id='') | Q(status='C')):
            # connect per-user since the escalations can be under different ship-tos
            try:
                i.gsx_account.connect(i.created_by)
            except Exception:
                continue # skip auth errors so we don't get stuck

            r = i.get_escalation().lookup()
            aware = timezone.make_aware(r.lastModifiedTimestamp, tz)

            if aware < i.updated_at: # hasn't been updated
                continue

            try:
                parent = i.note_set.latest()
            except Note.DoesNotExist:
                continue

            bodies = [n.body for n in i.note_set.all()]

            for x in r.escalationNotes.iterchildren():
                if x.text in bodies: # skip notes we already have
                    continue

                note = Note(created_by=user, escalation=i, body=x.text)
                parent.add_reply(note)
                note.save()

            i.updated_at = timezone.now()
            i.status = r.escalationStatus
            i.save() 
Example 23
Project: jbox   Author: jpush   File: fields.py    License: MIT License 5 votes vote down vote up
def process_formdata(self, valuelist):
        super(DateTimeField, self).process_formdata(valuelist)

        date = self.data

        if settings.USE_TZ and date is not None and timezone.is_naive(date):
            current_timezone = timezone.get_current_timezone()
            self.data = timezone.make_aware(date, current_timezone) 
Example 24
Project: django-angularjs-blog   Author: bluedazzle   File: utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def string_to_datetime(timestring, timeformat='%Y-%m-%d %H:%M:%S', usetz=True):
    dateres = datetime.datetime.strptime(timestring, timeformat)
    if usetz:
        tz = timezone.get_current_timezone()
        dateres = tz.localize(dateres)
        dateres = dateres.astimezone(tz)
    return dateres 
Example 25
Project: django-angularjs-blog   Author: bluedazzle   File: utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def datetime_to_timestamp(datetimet):
    if datetimet.tzinfo is None:
        return time.mktime(datetimet.timetuple())
    datetimet = datetimet.astimezone(timezone.get_current_timezone())
    return time.mktime(datetimet.timetuple()) 
Example 26
Project: django-angularjs-blog   Author: bluedazzle   File: utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def datetime_to_string(datetimet, str_format='%Y-%m-%d %H:%M:%S'):
    if datetimet.tzinfo is None:
        return datetimet.strftime(str_format)
    time_str = datetimet.astimezone(timezone.get_current_timezone())
    return time_str.strftime(str_format) 
Example 27
Project: django-angularjs-blog   Author: bluedazzle   File: TimeFormatFactory.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def datetime_to_string(datetime_time, time_format='%Y-%m-%d %H:%M:%S'):
        if datetime_time.tzinfo is None:
            return datetime_time.strftime(time_format)
        datetime_time = datetime_time.astimezone(timezone.get_current_timezone())
        return datetime_time.strftime(time_format) 
Example 28
Project: django-angularjs-blog   Author: bluedazzle   File: TimeFormatFactory.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def datetime_to_timestamp(datetime_time):
        if datetime_time.tzinfo is None:
            return time.mktime(datetime_time.timetuple())
        datetime_time = datetime_time.astimezone(timezone.get_current_timezone())
        return time.mktime(datetime_time.timetuple()) 
Example 29
Project: django-angularjs-blog   Author: bluedazzle   File: test_utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_convert(self):
        sample = string_to_datetime('2011-1-1 19:25:01')
        res = datetime_to_string(sample)
        self.assertEqual(res, '2011-01-01 19:25:01')
        sample.replace(tzinfo=get_current_timezone())
        res = datetime_to_string(sample)
        self.assertEqual(res, '2011-01-01 19:25:01') 
Example 30
Project: GTDWeb   Author: lanbing510   File: dates.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _make_date_lookup_arg(self, value):
        """
        Convert a date into a datetime when the date field is a DateTimeField.

        When time zone support is enabled, `date` is assumed to be in the
        current time zone, so that displayed items are consistent with the URL.
        """
        if self.uses_datetime_field:
            value = datetime.datetime.combine(value, datetime.time.min)
            if settings.USE_TZ:
                value = timezone.make_aware(value, timezone.get_current_timezone())
        return value