django.utils.timezone.get_current_timezone - python examples

Here are the examples of the python api django.utils.timezone.get_current_timezone taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

55 Examples 7

3 View Complete Implementation : ical.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def timezone(self):
        tzinfo = self.tzinfo()
        if getattr(tzinfo, 'zone', None):
            try:
                # Return the timezone unbound from the datetime
                return pytz.timezone(tzinfo.zone)
            except pytz.exceptions.UnknownTimeZoneError as e:
                raise CalendarTypeError(str(e)) from e
        elif tzinfo is not None:
            return tzinfo
        else:
            return timezone.get_current_timezone()

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : OkunaOrg
    def get(self, request):
        time = timezone.localtime(timezone.now())
        time_zone = get_current_timezone()

        return Response({
            'time': time,
            'timezone': str(time_zone)
        }, status=status.HTTP_200_OK)

3 View Complete Implementation : timeutils.py
Copyright MIT License
Author : ic-labs
def zero_datetime(dt, tz=None):
    """
    Return the given datetime with hour/minutes/seconds/ms zeroed and the
    timezone coerced to the given ``tz`` (or UTC if none is given).
    """
    if tz is None:
        tz = get_current_timezone()
    return coerce_naive(dt).replace(hour=0, minute=0, second=0, microsecond=0)

3 View Complete Implementation : serializers.py
Copyright MIT License
Author : learningequality
    def to_internal_value(self, data):
        data = super(DateTimeTzField, self).to_internal_value(data)
        tz = timezone.get_current_timezone()
        if not data.tzinfo:
            data = timezone.make_aware(data, pytz.utc)
        return data.astimezone(tz)

3 View Complete Implementation : defaulttags.py
Copyright MIT License
Author : rizwansoaib
    def render(self, context):
        tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None
        formatted = date(datetime.now(tz=tzinfo), self.format_string)

        if self.asvar:
            context[self.asvar] = formatted
            return ''
        else:
            return formatted

3 View Complete Implementation : models.py
Copyright GNU General Public License v3.0
Author : Ehco1996
    @clastmethod
    def cost_statistics(cls, good_id, start, end):
        start = pendulum.parse(start, tz=timezone.get_current_timezone())
        end = pendulum.parse(end, tz=timezone.get_current_timezone())
        query = cls.objects.filter(
            good__id=good_id, purchtime__gte=start, purchtime__lte=end
        )
        for obj in query:
            print(obj.user, obj.good)
        count = query.count()
        amount = count * obj.money
        print(
            "{} ~ {} 时间内 商品: {} 共销售 {} 次 总金额 {} 元".format(
                start.date(), end.date(), obj.good, count, amount
            )
        )

3 View Complete Implementation : telltime.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
def getLocalDatetime(date, time, tz=None, timeDefault=dt.time.max):
    """
    Get a datetime in the local timezone from date and optionally time
    """
    localTZ = timezone.get_current_timezone()
    if tz is None or tz == localTZ:
        localDt = getAwareDatetime(date, time, tz, timeDefault)
    else:
        # create in event's time zone
        eventDt = getAwareDatetime(date, time, tz, timeDefault)
        # convert to local time zone
        localDt = eventDt.astimezone(localTZ)
        if time is None:
            localDt = getAwareDatetime(localDt.date(), None, localTZ, timeDefault)
    return localDt

3 View Complete Implementation : tz.py
Copyright GNU General Public License v2.0
Author : blackye
@register.filter
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())

3 View Complete Implementation : models.py
Copyright GNU Lesser General Public License v3.0
Author : phith0n
def generate_image_filename(instance, filename):
    filename, ext = os.path.splitext(filename)
    filename = "%s-%s%s" % (uuid4(), get_random_string(length=8), ext)

    tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None
    date_dir = date(datetime.now(tz=tzinfo), 'Y/m/d')

    return "images/%s/%s" % (date_dir, filename)

3 View Complete Implementation : timeutils.py
Copyright MIT License
Author : ic-labs
def coerce_aware(dt, tz=None):
    if is_aware(dt):
        return dt
    else:
        if tz is None:
            tz = get_current_timezone()
        return make_aware(dt, tz)

3 View Complete Implementation : fields.py
Copyright MIT License
Author : learningequality
def parse_timezonestamp(value):
    if tz_regex.search(value):
        tz = pytz.timezone(tz_regex.search(value).groups()[0])
    else:
        tz = timezone.get_current_timezone()
    utc_value = tz_regex.sub("", value)
    value = typecast_timestamp(utc_value)
    if value.tzinfo is None:
        # Naive datetime, make aware
        value = timezone.make_aware(value, pytz.utc)
    return value.astimezone(tz)

3 View Complete Implementation : tests.py
Copyright MIT License
Author : silentsokolov
    @skipIf(pytz is None, 'install pytz')
    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.astertEqual(date.tzinfo.zone, local_tz.zone)
        self.astertTrue(timezone.is_aware(date))

        now = timezone.now()
        date = DateRangeFilter.make_dt_aware(now, local_tz)
        self.astertEqual(date.tzinfo.zone, local_tz.zone)
        self.astertTrue(timezone.is_aware(date))

3 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : edisonlz
    def year_lookup_bounds_for_datetime_field(self, value):
        """
        Returns 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)
        return [first, second]

3 View Complete Implementation : ical.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def datetime(self, timeDefault=dt.time.min):
        # TODO: Allow 'floating' times?
        tz = timezone.get_current_timezone()
        if type(self.dt) == dt.datetime:
            if timezone.is_aware(self.dt):
                return self.dt
            else:
                return timezone.make_aware(self.dt, tz)
        elif type(self.dt) == dt.date:
            return getAwareDatetime(self.dt, None, tz, timeDefault)

3 View Complete Implementation : shared.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
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()

3 View Complete Implementation : ical.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def _convertTZ(self):
        """Will convert UTC datetimes to the current local timezone"""
        tz = timezone.get_current_timezone()
        dtstart = self['DTSTART']
        dtend   = self['DTEND']
        if dtstart.zone() == "UTC":
            dtstart.dt = dtstart.dt.astimezone(tz)
        if dtend.zone() == "UTC":
            dtend.dt = dtend.dt.astimezone(tz)

3 View Complete Implementation : common_tags.py
Copyright GNU General Public License v2.0
Author : getway
@register.filter
def ts_to_date(ts):
    try:
        ts = float(ts)
    except (TypeError, ValueError):
        ts = 0
    dt = timezone.datetime.fromtimestamp(ts).\
        replace(tzinfo=timezone.get_current_timezone())
    return dt.strftime('%Y-%m-%d %H:%M:%S')

3 View Complete Implementation : models.py
Copyright MIT License
Author : moshthepitt
def get_days(start: object, end: object):
    """
    Yield the days between two datetime objects
    """
    current_tz = timezone.get_current_timezone()
    local_start = current_tz.normalize(start)
    local_end = current_tz.normalize(end)
    span = local_end.date() - local_start.date()
    for i in range(span.days + 1):
        yield local_start.date() + timedelta(days=i)

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
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)

3 View Complete Implementation : models.py
Copyright GNU Lesser General Public License v3.0
Author : phith0n
def generate_attachment_filename(instance, filename):
    filename, ext = os.path.splitext(filename)
    if ext not in ('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.rar', '.gz', '.zip', '.7z', '.txt', '.pdf',
                   '.doc', '.docx', '.ppt', '.pptx', ):
        ext = '.attach'
    filename = "%s-%s%s" % (uuid4(), get_random_string(length=8), ext)

    tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None
    date_dir = date(datetime.now(tz=tzinfo), 'Y/m')

    return "attachment/%s/%s" % (date_dir, filename)

3 View Complete Implementation : timeutils.py
Copyright MIT License
Author : ic-labs
def coerce_naive(dt, tz=None):
    if is_naive(dt):
        return dt
    else:
        if tz is None:
            tz = get_current_timezone()
        return make_naive(dt, tz)

3 View Complete Implementation : operations.py
Copyright MIT License
Author : rizwansoaib
    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]

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
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)

3 View Complete Implementation : tz.py
Copyright MIT License
Author : rizwansoaib
@register.filter
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())

3 View Complete Implementation : timeutils.py
Copyright MIT License
Author : ic-labs
def format_naive_ical_dt(date_or_datetime):
    """
    Return datetime formatted for use in iCal as a *naive* datetime value to
    work more like people expect, e.g. creating a series of events starting
    at 9am should not create some occurrences that start at 8am or 10am after
    a daylight savings change.
    """
    dt = coerce_dt_awareness(date_or_datetime)
    if is_naive(dt):
        return dt.strftime('%Y%m%dT%H%M%S')
    else:
        return dt.astimezone(get_current_timezone()).strftime('%Y%m%dT%H%M%S')

3 View Complete Implementation : dates.py
Copyright GNU General Public License v2.0
Author : blackye
    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 astumed 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

3 View Complete Implementation : cron.py
Copyright MIT License
Author : telminov
    def check_run_time(self):
        now = timezone.now().astimezone(timezone.get_current_timezone())
        templates_task = models.TaskTemplate.objects.exclude(cron='')
        for template_task in templates_task:
            if template_task.have_uncompleted_task():
                continue

            last_time = template_task.cron_dt.astimezone(timezone.get_current_timezone())
            next_time = croniter(template_task.cron, last_time).get_next(datetime.datetime).astimezone(timezone.get_current_timezone())
            if next_time <= now:
                self.run_task(template_task)
                template_task.cron_dt = timezone.now()
                template_task.save()

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def jr_two_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_two(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)

3 View Complete Implementation : operations.py
Copyright MIT License
Author : bpgc-cte
    def year_lookup_bounds_for_datetime_field(self, value):
        """
        Returns 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]

3 View Complete Implementation : schema.py
Copyright MIT License
Author : ivelum
    def get_lookup_value(self, value):
        if not value:
            return None
        mask = '%Y-%m-%d'
        if len(value) > 10:
            mask += ' %H:%M'
        if len(value) > 16:
            mask += ':%S'
        dt = datetime.strptime(value, mask)
        if settings.USE_TZ:
            dt = dt.replace(tzinfo=get_current_timezone())
        return dt

3 View Complete Implementation : forms.py
Copyright MIT License
Author : whitesmith
    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

0 View Complete Implementation : utils.py
Copyright GNU Affero General Public License v3.0
Author : andersroos
def localnow():
    """ Get the current datetime in the local timezone for the user
    (timezone set by timezone.activate())."""
    return timezone.localtime(utcnow(), timezone=timezone.get_current_timezone())

0 View Complete Implementation : utils.py
Copyright GNU Affero General Public License v3.0
Author : andersroos
def localtoday():
    """ Get the current date in the local timezone for the user
    (timezone set by timezone.activate())."""
    return timezone.localtime(utcnow(), timezone=timezone.get_current_timezone()).date()

0 View Complete Implementation : defaulttags.py
Copyright GNU General Public License v2.0
Author : blackye
    def render(self, context):
        tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None
        return date(datetime.now(tz=tzinfo), self.format_string)

0 View Complete Implementation : comicimporter.py
Copyright GNU General Public License v3.0
Author : bpepple
    def checkIfRemovedOrModified(self, comic, pathlist):
        remove = False

        def inFolderlist(filepath, pathlist):
            for p in pathlist:
                if p in filepath:
                    return True
            return False

        if not (os.path.exists(comic.file)):
            self.logger.info("Removing missing {0}".format(comic.file))
            remove = True
        elif not inFolderlist(comic.file, pathlist):
            self.logger.info("Removing unwanted {0}".format(comic.file))
            remove = True
        else:
            current_timezone = timezone.get_current_timezone()
            c = datetime.utcfromtimestamp(os.path.getmtime(comic.file))
            curr = timezone.make_aware(c, current_timezone)
            prev = comic.mod_ts

            if curr != prev:
                self.logger.info("Removing modified {0}".format(comic.file))
                remove = True

        if remove:
            series = Series.objects.get(id=comic.series.id)
            s_count = series.issue_count
            # If this is the only issue for a series, delete the series.
            if s_count == 1:
                series.delete()
                self.logger.info('Deleting series: %s' % series)
            else:
                comic.delete()

0 View Complete Implementation : comicimporter.py
Copyright GNU General Public License v3.0
Author : bpepple
    def addComicFromMetadata(self, md):
        if not md.isEmpty:
            # Let's get the issue Comic Vine id from the archive's metadata
            # If it's not there we'll skip the issue.
            cvID = self.getIssueCVID(md)
            if cvID is None:
                issue_name = md.series + ' #' + md.number
                self.logger.info(
                    'No Comic Vine ID for: %s... skipping.' % issue_name)
                return False

            # let's get the issue info from CV.
            issue_response = self.getIssue(cvID)
            if issue_response is None:
                return False

            # Add the Publisher to the database.
            if md.publisher is not None:
                publisher_obj, p_create = Publisher.objects.get_or_create(
                    name=md.publisher,
                    slug=slugify(md.publisher),)

            # Check the series cvid to see if we've already added
            # the series. If not, call the detail api for it.
            series_cvid = issue_response['results']['volume']['id']
            if series_cvid is not None:
                series_obj, s_create = Series.objects.get_or_create(
                    cvid=int(series_cvid),)
                if s_create:
                    series_url = issue_response['results'][
                        'volume']['api_detail_url']
                    data = self.getSeries(series_url)
                    if data is not None:
                        # Create the slug & make sure it's not a duplicate
                        new_slug = orig = slugify(data['name'])
                        for x in itertools.count(1):
                            if not Series.objects.filter(slug=new_slug).exists():
                                break
                            new_slug = '%s-%d' % (orig, x)

                        sort_name = utils.create_series_sortname(data['name'])
                        series_obj.slug = new_slug
                        series_obj.cvurl = data['cvurl']
                        series_obj.name = data['name']
                        series_obj.sort_satle = sort_name
                        series_obj.publisher = publisher_obj
                        series_obj.year = data['year']
                        series_obj.desc = data['desc']
                        series_obj.save()
                        self.logger.info('Added series: %s' % series_obj)

            # Ugh, deal wih the timezone
            current_timezone = timezone.get_current_timezone()
            tz = timezone.make_aware(md.mod_ts, current_timezone)

            pub_date = None
            if md.year is not None:
                try:
                    day = 1
                    month = 1
                    if md.month is not None:
                        month = int(md.month)
                    if md.day is not None:
                        day = int(md.day)
                    year = int(md.year)
                    pub_date = datetime(year, month, day)
                except:
                    past

            fixed_number = IssueString(md.issue).asttring(pad=3)

            if pub_date is not None:
                slugy = series_obj.name + ' ' + \
                    fixed_number + ' ' + str(pub_date.year)
            else:
                slugy = series_obj.name + ' ' + fixed_number

            new_slug = orig = slugify(slugy)

            for x in itertools.count(1):
                if not Issue.objects.filter(slug=new_slug).exists():
                    break
                new_slug = '%s-%d' % (orig, x)

            try:
                # Create the issue
                issue_obj = Issue.objects.create(
                    file=md.path,
                    name=str(md.satle),
                    slug=new_slug,
                    number=fixed_number,
                    date=pub_date,
                    page_count=md.page_count,
                    cvurl=md.webLink,
                    cvid=int(cvID),
                    mod_ts=tz,
                    series=series_obj,)
            except IntegrityError as e:
                self.logger.error('%s' % e)
                self.logger.info('Skipping: %s' % md.path)
                return

            # Set the issue image & short description.
            res = self.setIssueDetail(cvID, issue_response)
            if res:
                self.logger.info("Added: %s" % issue_obj)
            else:
                self.logger.warning(
                    'No detail information was saved for %s' % issue_obj)

            # Adding new publisher we need to grab
            # some additional data from Comic Vine.
            if p_create:
                p = self.getPublisher(issue_response)
                if p is not None:
                    publisher_obj.cvid = int(p['cvid'])
                    publisher_obj.cvurl = p['cvurl']
                    publisher_obj.desc = p['desc']
                    publisher_obj.save()
                    if p['image'] is not '':
                        publisher_obj.logo = utils.resize_images(p['image'],
                                                                 PUBLISHERS_FOLDER)
                        # Delete the original image
                        os.remove(p['image'])
                    self.logger.info('Added publisher: %s' % publisher_obj)

            # Add the characters.
            for ch in issue_response['results']['character_credits']:
                character_obj, ch_create = Character.objects.get_or_create(
                    cvid=ch['id'],)
                issue_obj.characters.add(character_obj)

                if ch_create:
                    new_slug = orig = slugify(ch['name'])
                    for x in itertools.count(1):
                        if not Character.objects.filter(slug=new_slug).exists():
                            break
                        new_slug = '%s-%d' % (orig, x)

                    character_obj.name = ch['name']
                    character_obj.slug = new_slug
                    character_obj.save()
                    # Alright get the detail information now.
                    res = self.getDetailInfo(character_obj,
                                             self.character_fields,
                                             ch['api_detail_url'])

                    if character_obj.image:
                        self.create_images(character_obj, CHARACTERS_FOLDERS)

                    if res:
                        self.logger.info('Added character: %s' % character_obj)
                    else:
                        self.logger.warning(
                            'No Character detail was saved for: %s' % character_obj)

            # Add the storyarc.
            for story_arc in issue_response['results']['story_arc_credits']:
                story_obj, s_create = Arc.objects.get_or_create(
                    cvid=story_arc['id'],)
                issue_obj.arcs.add(story_obj)

                if s_create:
                    new_slug = orig = slugify(story_arc['name'])
                    for x in itertools.count(1):
                        if not Arc.objects.filter(slug=new_slug).exists():
                            break
                        new_slug = '%s-%d' % (orig, x)

                    story_obj.name = story_arc['name']
                    story_obj.slug = new_slug
                    story_obj.save()

                    res = self.getDetailInfo(story_obj,
                                             self.arc_fields,
                                             story_arc['api_detail_url'])

                    if story_obj.image:
                        self.create_images(story_obj, ARCS_FOLDER)

                    if res:
                        self.logger.info('Added storyarc: %s' % story_obj)
                    else:
                        self.logger.info('Not Story Arc detail info available for: %s'
                                         % story_obj)

            # Add the teams
            for team in issue_response['results']['team_credits']:
                team_obj, t_create = Team.objects.get_or_create(
                    cvid=team['id'],)
                issue_obj.teams.add(team_obj)

                # Add any existing character to the team.
                c_response = self.getTeamCharacters(team['api_detail_url'])
                if c_response is not None:
                    for character in c_response['results']['characters']:
                        match = Character.objects.filter(cvid=character['id'])
                        if match:
                            match[0].teams.add(team_obj)

                if t_create:
                    new_slug = orig = slugify(team['name'])
                    for x in itertools.count(1):
                        if not Team.objects.filter(slug=new_slug).exists():
                            break
                        new_slug = '%s-%d' % (orig, x)

                    team_obj.name = team['name']
                    team_obj.slug = new_slug
                    team_obj.save()

                    res = self.getDetailInfo(team_obj,
                                             self.team_fields,
                                             team['api_detail_url'])

                    if team_obj.image:
                        self.create_images(team_obj, TEAMS_FOLDERS)

                    if res:
                        self.logger.info('Added team: %s' % team_obj)
                    else:
                        self.logger.info('No Team detail info available for: %s'
                                         % team_obj)

            # Add the creators
            for p in issue_response['results']['person_credits']:
                creator_obj, c_create = Creator.objects.get_or_create(
                    cvid=p['id'],)

                role_obj = Roles.objects.create(
                    creator=creator_obj, issue=issue_obj)

                roles = p['role'].split(',')
                for role in roles:
                    # Remove any whitespace
                    role = role.strip()
                    r, r_create = Role.objects.get_or_create(name=role.satle())
                    role_obj.role.add(r)

                if c_create:
                    new_slug = orig = slugify(p['name'])
                    for x in itertools.count(1):
                        if not Creator.objects.filter(slug=new_slug).exists():
                            break
                        new_slug = '%s-%d' % (orig, x)

                    creator_obj.name = p['name']
                    creator_obj.slug = new_slug
                    creator_obj.save()

                    res = self.getDetailInfo(creator_obj,
                                             self.creator_fields,
                                             p['api_detail_url'])

                    if creator_obj.image:
                        self.create_images(creator_obj, CREATORS_FOLDERS)

                    if res:
                        self.logger.info('Added creator: %s' % creator_obj)
                    else:
                        self.logger.info('No Creator detail info available for: %s'
                                         % creator_obj)

            return True

0 View Complete Implementation : utils.py
Copyright MIT License
Author : datosgobar
def kong_milliseconds_to_tzdatetime(timestamp):
    return datetime.fromtimestamp(milliseconds_to_seconds(timestamp), get_current_timezone())

0 View Complete Implementation : serializers.py
Copyright Apache License 2.0
Author : erigones
    def get_filters(self, pending_tasks=()):
        if self._object_pks is not None and not self._object_pks:  # Means that we want to return empty filter results
            return False

        tz = timezone.get_current_timezone()
        data = self.object
        query = []

        date_from = data.get('date_from')
        if date_from:
            date_from = datetime.combine(date_from, datetime.min.time())
            query.append(Q(time__gte=date_from.replace(tzinfo=utc).astimezone(tz)))

        date_to = data.get('date_to')
        if date_to:
            date_to = datetime.combine(date_to, datetime.min.time())
            query.append(Q(time__lte=date_to.replace(tzinfo=utc).astimezone(tz)))

        if self._object_pks:
            query.append(Q(object_pk__in=self._object_pks))

        status = data.get('status')
        if status:
            query.append(Q(status=status))

        if data.get('show_running'):
            query.append(Q(task__in=pending_tasks))

        object_type = data.get('content_type')
        if object_type:
            if self._content_type:
                content_type = self._content_type
            else:
                content_type = ContentType.objects.get(model=object_type)
            query.append(Q(content_type=content_type))

        if data.get('hide_auto'):
            query.append(~Q(task_type__in=get_task_types(tt=(TT_AUTO,))))

        if query:
            return reduce(and_, query)
        else:
            return None

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : erigones
    def clean(self):
        cleaned_data = super(BaseAlertFilterForm, self).clean()

        if self._errors:
            return cleaned_data

        data = cleaned_data.copy()
        tz = timezone.get_current_timezone()

        if data['since']:
            data['since'] = data['since'].replace(tzinfo=tz).astimezone(utc).strftime('%s')

        if data['until']:
            data['until'] = data['until'].replace(tzinfo=tz).astimezone(utc).strftime('%s')

        show_nodes = data.pop('show_nodes', False)

        if data.get('show_all', False):
            data['dc_bound'] = False
        else:
            data['dc_bound'] = not show_nodes

        self._remove_empty_fields(data)
        ser = AlertSerializer(self._request, data=data)

        if ser.is_valid():
            api_data = ser.data
            # Not used filters
            del api_data['last']
            del api_data['node_uuids']
            del api_data['vm_uuids']

            if not self._request.user.is_staff:  # SuperAdmin only fields
                del api_data['node_hostnames']
                del api_data['show_all']
                api_data['dc_bound'] = True

            self.api_data = self._remove_empty_fields(api_data)
        else:
            self.api_data = None
            self._set_api_errors(ser.errors)

        return cleaned_data

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : erigones
    def clean_schedule(self):
        """Time in schedule in templates is timezone aware. Change to UTC."""
        data = self.cleaned_data.get('schedule')

        try:
            schedule = data.split()
            hour = schedule[1]
            if '*' in hour:
                raise IndexError
        except IndexError:
            return data

        tz = timezone.get_current_timezone()
        now_local = datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(tz)

        def to_utc(match):
            num = int(match.group(0))
            now = now_local.replace(hour=num)
            return str(pytz.utc.normalize(now).hour)

        try:
            schedule[1] = re.sub(r'(\d+)', to_utc, hour)
        except ValueError:
            return data

        return ' '.join(schedule)

0 View Complete Implementation : admin.py
Copyright MIT License
Author : ic-labs
    def calendar_data(self, request):
        """
        Return event data in JSON format for AJAX requests, or a calendar page
        to be loaded in an iframe.
        """

        # mutable copy
        request.GET = request.GET.copy()

        if 'timezone' in request.GET:
            tz = djtz.get(request.GET.pop('timezone'))
        else:
            tz = get_current_timezone()

        if 'start' in request.GET:
            start_dt = self._parse_dt_from_request(request, 'start')
            if start_dt:
                start = djtz.localize(start_dt, tz)
            else:
                start = None
        else:
            start = None
        if 'end' in request.GET:
            end_dt = self._parse_dt_from_request(request, 'end')
            if end_dt:
                end = djtz.localize(end_dt, tz)
            else:
                end = None
        else:
            end = None

        # filter the qs like the changelist filters
        cl = ChangeList(request, self.model, self.list_display,
                        self.list_display_links, self.list_filter,
                        self.date_hierarchy, self.search_fields,
                        self.list_select_related, self.list_per_page,
                        self.list_max_show_all, self.list_editable, self)

        filtered_event_ids = cl.get_queryset(request).values_list('id', flat=True)
        all_occurrences = models.Occurrence.objects.filter(event__id__in=filtered_event_ids).overlapping(start, end)

        data = []
        for occurrence in all_occurrences.all():
            data.append(self._calendar_json_for_occurrence(occurrence))
        data = json.dumps(data, cls=DjangoJSONEncoder)
        return HttpResponse(content=data, content_type='application/json')

0 View Complete Implementation : extraction.py
Copyright GNU General Public License v3.0
Author : jjerphan
def save_tweet(tweet, user):
    """Saves one tweet from user in database"""
    newTweet = Tweet()
    newTweet.id = tweet['id']
    newTweet.user_id = user
    newTweet.text = tweet['text']
    newTweet.created_at = tweet['created_at']
    newTweet.is_quote_status = tweet['is_quote_status']
    newTweet.in_reply_to_status_id = tweet['in_reply_to_status_id']
    newTweet.favorite_count = tweet['favorite_count']
    newTweet.retweet_count = tweet['retweet_count']
    newTweet.source = tweet['source']
    newTweet.in_reply_to_user_id = tweet['in_reply_to_user_id']
    newTweet.lang = tweet['lang']
    newTweet.tokenArray = tweet['tokenArray']
    newTweet.lemmaArray = tweet['lemmaArray']

    # Formating the date
    current_tz = timezone.get_current_timezone()
    newTweet.created_at = datetime.strptime(newTweet.created_at, '%a %b %d %H:%M:%S +0000 %Y')
    newTweet.created_at = current_tz.localize(newTweet.created_at)
    # newTweet.created_at = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(newTweet.created_at,'%a %b %d %H:%M:%S +0000 %Y'))

    # Saving the tweet
    try:
        newTweet.save()
        return True
    except BaseException as error:
        print("saveTweet() ; error : ", error)
        return False

0 View Complete Implementation : extraction.py
Copyright GNU General Public License v3.0
Author : jjerphan
def save_user(userInfo):
    """Saves one user in database"""
    newUser = User()

    newUser.id = userInfo['id']
    newUser.name = userInfo['name']
    newUser.screen_name = userInfo['screen_name']
    newUser.created_at = userInfo['created_at']
    newUser.contributors_enabled = userInfo['contributors_enabled']
    newUser.verified = userInfo['verified']
    newUser.description = userInfo['description']
    newUser.followers_count = userInfo['followers_count']
    newUser.profile_image_url = userInfo['profile_image_url']

    # Formating the date
    current_tz = timezone.get_current_timezone()
    newUser.created_at = datetime.strptime(newUser.created_at, '%a %b %d %H:%M:%S +0000 %Y')
    newUser.created_at = current_tz.localize(newUser.created_at)
    # newUser.created_at = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(newUser.created_at,'%a %b %d %H:%M:%S +0000 %Y'))

    # Saving the user in the database
    try:
        newUser.save()
        return True
    except BaseException as error:
        print("saveUser() ; error : ", error)
        return False

0 View Complete Implementation : ical.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def load(self, request, data, name=""):
        if self.page is None:
            raise CalendarNotInitializedError("No page set")

        # Typically, this information will consist of an iCalendar stream
        # with a single iCalendar object.  However, multiple iCalendar
        # objects can be sequentially grouped together in an iCalendar
        # stream.
        try:
            calStream = Calendar.from_ical(data, multiple=True)
        except ValueError as e:
            messages.error(request, "Could not parse iCalendar file "+name)
            #messages.debug(request, str(e))
            return

        self.clear()
        numSuccess = numFail = 0
        for cal in calStream:
            tz = timezone.get_current_timezone()
            zone = cal.get('X-WR-TIMEZONE', None)
            if zone:
                try:
                    tz = pytz.timezone(zone)
                except pytz.exceptions.UnknownTimeZoneError:
                    messages.warning(request, "Unknown time zone {}".format(zone))
            with timezone.override(tz):
                result = self._loadEvents(request, cal.walk(name="VEVENT"))
                numSuccess += result[0]
                numFail    += result[1]
        if numSuccess:
            messages.success(request, "{} iCal events loaded".format(numSuccess))
        if numFail:
            messages.error(request, "Could not load {} iCal events".format(numFail))

0 View Complete Implementation : test_urls.py
Copyright BSD 2-Clause "Simplified" License
Author : neon-jungle
def dt(*args):
    return datetime.datetime(*args, tzinfo=timezone.get_current_timezone())

0 View Complete Implementation : test_datetimefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @requires_tz_support
    @skipUnlessDBFeature('has_zoneinfo_database')
    @override_settings(USE_TZ=True, TIME_ZONE='America/Vancouver')
    def test_lookup_date_with_use_tz(self):
        d = datetime.date(2014, 3, 12)
        # The following is equivalent to UTC 2014-03-12 18:34:23.24000.
        dt1 = datetime.datetime(2014, 3, 12, 10, 22, 23, 240000, tzinfo=timezone.get_current_timezone())
        # The following is equivalent to UTC 2014-03-13 05:34:23.24000.
        dt2 = datetime.datetime(2014, 3, 12, 21, 22, 23, 240000, tzinfo=timezone.get_current_timezone())
        t = datetime.time(21, 22, 23, 240000)
        m1 = DateTimeModel.objects.create(d=d, dt=dt1, t=t)
        m2 = DateTimeModel.objects.create(d=d, dt=dt2, t=t)
        # In Vancouver, we expect both results.
        self.astertQuerysetEqual(
            DateTimeModel.objects.filter(dt__date=d),
            [repr(m1), repr(m2)],
            ordered=False
        )
        with self.settings(TIME_ZONE='UTC'):
            # But in UTC, the __date only matches one of them.
            self.astertQuerysetEqual(DateTimeModel.objects.filter(dt__date=d), [repr(m1)])

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_partial_index(self):
        with connection.schema_editor() as editor:
            index = Index(
                name='recent_article_idx',
                fields=['pub_date'],
                condition=Q(
                    pub_date__gt=datetime.datetime(
                        year=2015, month=1, day=1,
                        # PostgreSQL would otherwise complain about the lookup
                        # being converted to a mutable function (by removing
                        # the timezone in the cast) which is forbidden.
                        tzinfo=timezone.get_current_timezone(),
                    ),
                )
            )
            self.astertIn(
                'WHERE %s.%s' % (editor.quote_name(Article._meta.db_table), editor.quote_name("pub_date")),
                str(index.create_sql(Article, schema_editor=editor))
            )
            editor.add_index(index=index, model=Article)
            self.astertIn(index.name, connection.introspection.get_constraints(
                cursor=connection.cursor(), table_name=Article._meta.db_table,
            ))
            editor.remove_index(index=index, model=Article)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnlessDBFeature('supports_functions_in_partial_indexes')
    def test_multiple_conditions(self):
        with connection.schema_editor() as editor:
            index = Index(
                name='recent_article_idx',
                fields=['pub_date', 'headline'],
                condition=(
                    Q(pub_date__gt=datetime.datetime(
                        year=2015,
                        month=1,
                        day=1,
                        tzinfo=timezone.get_current_timezone(),
                    )) & Q(headline__contains='China')
                ),
            )
            sql = str(index.create_sql(Article, schema_editor=editor))
            where = sql.find('WHERE')
            self.astertIn(
                'WHERE (%s.%s' % (editor.quote_name(Article._meta.db_table), editor.quote_name("pub_date")),
                sql
            )
            # Because each backend has different syntax for the operators,
            # check ONLY the occurrence of headline in the SQL.
            self.astertGreater(sql.rfind('headline'), where)
            editor.add_index(index=index, model=Article)
            self.astertIn(index.name, connection.introspection.get_constraints(
                cursor=connection.cursor(), table_name=Article._meta.db_table,
            ))
            editor.remove_index(index=index, model=Article)

0 View Complete Implementation : import_basedata.py
Copyright MIT License
Author : OKFNat
	def import_elections(self, elections, config):
		"""
		Import elections data into database.
		"""

		num_entries_created = 0
		num_entries_updated = 0

		for key, value in elections.items():
			ts = datetime.datetime.strptime(value['election_day'], '%Y-%m-%d')
			ts = timezone.make_aware(ts, timezone.get_current_timezone())

			e = Election.objects.update_or_create(
				short_name = value['short_name'],
				short_name_text = value['short_name_text'],
				full_name = value['full_name'],
				election_type = value['election_type'],
				wikidata_id = value['wikidata_id'],
				administrative_level = value['administrative_level'],
				election_day = ts,
				status = value['status']
			)
			if e[1] == True:
				if config['log_detail'] == 'high':
					print('New election entry "'+value['short_name']+'" created.')
				num_entries_created += 1
			else:
				if config['log_detail'] == 'high':
					print('Election entry "'+value['short_name']+'" updated.')
				num_entries_updated += 1

		print('Election table imported: '+ 'new entries: '+str(num_entries_created)+', updated entries: '+str(num_entries_updated))

0 View Complete Implementation : import_result.py
Copyright MIT License
Author : OKFNat
	def import_results(self, data, config):
		"""
		Imports results to database.
		"""

		ps_not_found = []
		psr_num_entries_created = 0
		psr_num_entries_updated = 0
		lr_num_entries_created = 0
		lr_num_entries_updated = 0

		for mun in data:
			mun_code = mun[config['spatial_id']]
			elec_short = config['election_short']

			# get timestamp of election result and convert it to server timezone
			if 'timestamp' in config:
				ts = datetime.datetime.strptime(config['timestamp'], '%Y-%m-%d %H:%M:%SZ')
			else:
				ts = datetime.datetime.strptime(mun['timestamp'], '%Y-%m-%d %H:%M:%SZ')
			ts = timezone.make_aware(ts, timezone.get_current_timezone())

			# Get eligible voters. Set to none if not in results
			if config['eligible_voters']:
				eligible_voters = mun['eligible_voters']
			else:
				eligible_voters = None

			# check type of polling station: municipality, regional_electoral_district, state, district, country
			if len(mun_code) == 6:
				mun_code = mun_code[1:6]
				if config['log_detail'] == 'high':
					print("Municipality code shortened from 6 to 5 digits.")
			not_country = not mun_code[:1] == '0'
			not_state = not mun_code[1:5] == '0000'
			not_red = mun_code[1:2].isdigit()
			not_district = not mun_code[3:5] == '00'
			not_absentee_ballot = not mun_code[3:5] == '99'

			if not_country and not_state and not_red and not_district and not_absentee_ballot:
				try:
					if config['spatial_id'] == 'municipality_code':
						ps = PollingStation.objects.get(municipality__code=mun['municipality_code'])
					elif config['spatial_id'] == 'municipality_kennzahl':
						ps = PollingStation.objects.get(municipality__kennzahl=mun['municipality_kennzahl'])
					psr = PollingStationResult.objects.update_or_create(
						polling_station = ps,
						election = config['election_queryset'],
						eligible_voters = eligible_voters,
						votes = mun['votes'],
						valid = mun['valid'],
						invalid = mun['invalid'],
						ts_result = ts
					)
					if psr[1] == True:
						if config['log_detail'] == 'high':
							print('New pollingStationResult "'+psr[0]+'" created.')
						psr_num_entries_created += 1
					else:
						if config['log_detail'] == 'high':
							print('PollingStationResult "'+psr[0]+'" updated.')
						psr_num_entries_updated += 1

					for key, value in config['lists_queryset'].items():
						if mun[key] == 'None':
							votes = None
						else:
							votes = mun[key]

						lr = ListResult.objects.update_or_create(
							polling_station_result = psr[0],
							election_list = value,
							votes = votes
						)
						if lr[1] == True:
							if config['log_detail'] == 'high':
								print('New ListResult "'+lr[0]+'" created.')
							lr_num_entries_created += 1
						else:
							if config['log_detail'] == 'high':
								print('ListResult "'+lr[0]+'" updated.')
							lr_num_entries_updated += 1

				except Exception as e:
					if config['log_detail'] == 'middle' and config['log_detail'] == 'high':
						print('Warning: PollingStation {} not found.'.format(mun['municipality_code']))
					ps_not_found.append(mun['municipality_code'])
			else:
				print('Municipality ' + mun_code + ' not stored in database, cause no municipality.')

		config['psr-entries_created'] = psr_num_entries_created
		config['psr-entries_updated'] = psr_num_entries_updated
		config['lr-entries_created'] = lr_num_entries_created
		config['lr-entries_updated'] = lr_num_entries_updated
		print('PollingStationResult table imported: '+ 'new entries: '+str(psr_num_entries_created)+', updated entries: '+str(psr_num_entries_updated))
		print('ListResult table imported: '+ 'new entries: '+str(lr_num_entries_created)+', updated entries: '+str(lr_num_entries_updated))
		print('These polling stations where not found:', ps_not_found)