Python django.utils.timezone.get_current_timezone() Examples

The following are 30 code examples of django.utils.timezone.get_current_timezone(). 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: tests.py    From bennedetto with 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 #2
Source File: escalation_helper.py    From openduty with 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 #3
Source File: utils.py    From Hands-On-Application-Development-with-PyCharm with 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 #4
Source File: crawlers.py    From woid with 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 #5
Source File: query.py    From GTDWeb with 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
Source File: tz.py    From GTDWeb with 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 #7
Source File: tz.py    From Hands-On-Application-Development-with-PyCharm with 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 #8
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with 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 #9
Source File: utils.py    From GTDWeb with 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 #10
Source File: query.py    From Hands-On-Application-Development-with-PyCharm with 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 #11
Source File: tests.py    From bennedetto with 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 #12
Source File: imagemodels.py    From django-leonardo with 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 #13
Source File: utils.py    From srvup-rest-framework with 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 #14
Source File: query.py    From bioforum with 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 #15
Source File: tz.py    From bioforum with 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 #16
Source File: test_viewsets.py    From resolwe with 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 #17
Source File: forms.py    From hawkpost with 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 #18
Source File: test_filtering.py    From resolwe with 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 #19
Source File: shared.py    From janeway with 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 #20
Source File: utils.py    From bioforum with 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 #21
Source File: views.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def index(request):
    """
    Draw the home page.
    """
    page_length = UserSettings.get_page_length(request)
    newest_events = Event.all_visible.exclude(entries=None).prefetch_related('entries', 'tags')[:page_length]
    events_count = Event.all_visible.filter().count()
    entries_count = Entry.all_visible.filter().count()
    audio_sources_count = AudioSource.all_visible.filter().count()

    new_sources = []
    new_sources.extend(AudioSource.all_visible.order_by('-created_date')[:5])
    new_sources.extend(ImageSource.all_visible.order_by('-created_date')[:5])
    new_sources.sort(key=lambda source: source.created_date or
                                        timezone.datetime(1900, 1, 1, tzinfo=timezone.get_current_timezone()),
                     reverse=True)
    new_sources = new_sources[:5]

    related_sites = RelatedSite.objects.all()

    welcome_text = get_config('index_hello')

    return render(request, 'palanaeum/index.html', {'newest_events': newest_events, 'events_count': events_count,
                                                    'entries_count': entries_count, 'audio_sources_count': audio_sources_count,
                                                    'new_sources': new_sources, 'related_sites': related_sites,
                                                    'welcome_text': welcome_text}) 
Example #22
Source File: tz_utils.py    From django-radio with GNU General Public License v3.0 5 votes vote down vote up
def transform_datetime_tz(dt, tz=None):
    """
    Transform a datetime in other timezone to the current one
    """
    if not tz:
        tz = timezone.get_current_timezone()
    return tz.normalize(dt.astimezone(tz)) 
Example #23
Source File: tz_utils.py    From django-radio with GNU General Public License v3.0 5 votes vote down vote up
def get_active_timezone():
    """
    Same method as timezone.get_current_timezone but returning utc if nothing was set
    """
    return getattr(timezone._active, "value", pytz.utc) 
Example #24
Source File: views.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def jr_one_all_dates(request, output_format, start_year, start_month, start_day, end_year, end_month, end_day,
                     compat=False, report_request_id='', requestor_id='', requestor_email='', requestor_name='',
                     customer_ID='', customer_name=''):
    return jr_one(request, output_format,
                  timezone.datetime(int(start_year), int(start_month), int(start_day),
                                    tzinfo=timezone.get_current_timezone()),
                  timezone.datetime(int(end_year), int(end_month), int(end_day),
                                    tzinfo=timezone.get_current_timezone()),
                  compat, report_request_id, requestor_id, requestor_email, requestor_name, customer_ID,
                  customer_name) 
Example #25
Source File: views.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def jr_one_goa_all_dates(request, output_format, start_year, start_month, start_day, end_year, end_month, end_day,
                         compat=False, report_request_id='', requestor_id='', requestor_email='', requestor_name='',
                         customer_ID='', customer_name=''):
    return jr_one_goa(request, output_format,
                      timezone.datetime(int(start_year), int(start_month), int(start_day),
                                        tzinfo=timezone.get_current_timezone()),
                      timezone.datetime(int(end_year), int(end_month), int(end_day),
                                        tzinfo=timezone.get_current_timezone()),
                      compat, report_request_id, requestor_id, requestor_email, requestor_name, customer_ID,
                      customer_name) 
Example #26
Source File: TimeFormatFactory.py    From django-simple-serializer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def datetime_to_timestamp(datetime_time, time_format=None):
        if isinstance(datetime_time, datetime.datetime):
            if datetime_time.tzinfo:
                datetime_time = datetime_time.astimezone(timezone.get_current_timezone())
            return time.mktime(datetime_time.timetuple())
        return time.mktime(datetime_time.timetuple()) 
Example #27
Source File: TimeFormatFactory.py    From django-simple-serializer with 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 isinstance(datetime_time, datetime.datetime):
            if datetime_time.tzinfo:
                datetime_time = datetime_time.astimezone(timezone.get_current_timezone())
            return datetime_time.strftime(time_format)
        elif isinstance(datetime_time, datetime.time):
            time_format = '%H:%M:%S'
        elif isinstance(datetime_time, datetime.date):
            time_format = '%Y-%m-%d'
        return datetime_time.strftime(time_format) 
Example #28
Source File: wordpress_to_wagtail.py    From wagtail_blog with Apache License 2.0 5 votes vote down vote up
def create_comment(
        self, blog_post_type, blog_post_id, comment_text, date
    ):
        # Assume that the timezone wanted is the one that's active during parsing
        if date is not None and settings.USE_TZ and timezone.is_naive(date):
            date = timezone.make_aware(date, timezone.get_current_timezone())

        new_comment = XtdComment.objects.get_or_create(
            site_id=self.site_id,
            content_type=blog_post_type,
            object_pk=blog_post_id,
            comment=comment_text,
            submit_date=date,
        )[0]
        return new_comment 
Example #29
Source File: tests.py    From django-admin-rangefilter with MIT License 5 votes vote down vote up
def test_make_dt_aware_with_pytz(self):
        local_tz = timezone.get_current_timezone()
        now = datetime.datetime.now()
        date = DateRangeFilter.make_dt_aware(now, local_tz)

        self.assertEqual(date.tzinfo.zone, local_tz.zone)
        self.assertTrue(timezone.is_aware(date))

        now = timezone.now()
        date = DateRangeFilter.make_dt_aware(now, local_tz)
        self.assertEqual(date.tzinfo.zone, local_tz.zone)
        self.assertTrue(timezone.is_aware(date)) 
Example #30
Source File: helper.py    From openduty with MIT License 5 votes vote down vote up
def generate_notifications_for_user(incident, user, delay=None, preparedmsg = None):

        now = timezone.make_aware(datetime.now(), timezone.get_current_timezone())
        current_time = now
        notifications = []
        methods = user.notification_methods.order_by('position').all()
        method_index = 0

        for method in methods:
            if delay is None:
                notification_time = incident.service_key.retry * method_index + incident.service_key.escalate_after
            else:
                notification_time = method_index * delay
            notify_at = current_time + timedelta(minutes=notification_time)
            notification = ScheduledNotification()
            notification.incident = incident
            notification.user_to_notify = user
            notification.notifier = method.method
            notification.send_at = notify_at
            if preparedmsg is None:
                uri = settings.BASE_URL + "/incidents/details/" + str(incident.id)
                notification.message = "A Service is experiencing a problem: " + incident.incident_key + " " + incident.description + ". Handle at: " + uri
            else:
                notification.message = preparedmsg
            notifications.append(notification)
            print "Notify %s at %s with method: %s" % (user.username, notify_at, notification.notifier)
            method_index += 1

        # todo: error handling
        return notifications